堆 vs 数据段 vs 栈分配

16

我正在看以下程序,不确定内存是如何分配的以及为什么会这样:

void function() {
    char text1[] = "SomeText";
    const char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}
在上面的代码中,最后一个显然在堆上。然而,据我所知,text2 在程序的数据段中,而text1 可能在栈上。或者我的假设是错误的?这里的正确假设是什么?这是否取决于编译器?

2
+1:非常有趣的问题。 - Heisenbug
1
你理解指针和它所指向的数据之间的区别吗? - n0rd
是的,n0rd,但是这个似乎有多种可能的选择。 - Kiran
1
这是一个很好的面试问题 :) - lang2
text1text2text本身都在栈上。但是"..."在文本段中。从malloc获得的分配内存位于堆中。 - rosshjb
2个回答

19
// Array allocated on the stack and initialized with "SomeText" string.
// It has automatic storage duration. You shouldn't care about freeing memory.
char text1[] = "SomeText"; 

// Pointer to the constant string "Some Text".
// It has static storage duration. You shouldn't care about freeing memory.
// Note that it should be "a pointer to const".
// In this case you'll be protected from accidential changing of 
// the constant data (changing constant object leads to UB).
const char* text2 = "Some Text";

// malloc will allocate memory on the heap. 
// It has dynamic storage duration. 
// You should call "free" in the end to avoid memory leak.
char *text = (char*) malloc(strlen("Some Text") + 1 );

2
如果您取消text2的常量性并尝试修改它,会发生什么?这会导致段错误吗? - Drew Noakes
1
是的。这将导致一个段错误。 - Jagannath
1
@DrewNoakes 这是未定义行为。它可能会导致段错误,但你不能指望它。 - Kirill V. Lyadvinsky

5

是的,对于大多数系统:

text1 将是一个可写的变量数组在栈上(它必须是一个可写的数组)

text2 实际上必须是const char*,是的,它将指向可执行文件的文本段(但在不同的可执行文件格式中可能会改变)

text 将在堆上


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接