堆与数据段对堆栈分配

Kir*_*ran 15 c++ heap stack

我正在查看以下程序,并不确定如何分配内存以及原因:

void function() {
    char text1[] = "SomeText";
    char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,最后一个显然在堆中.但是,据我所知,text2位于程序的数据段中,而text1可能位于堆栈中.或者我的假设错了?这里的正确假设是什么?这个编译器是否依赖?

谢谢

Kir*_*sky 16

// 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 );
Run Code Online (Sandbox Code Playgroud)

  • 如果您放弃“text2”的常量并尝试修改它,会发生什么?这是段错误吗? (2认同)

Let*_*_Be 5

是的,你是对的,在大多数系统上:

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

text2必须是const char*实际的,是的,它将指向可执行文件的一个文本段(但可能会在可执行格式中发生变化)

text 将在堆上