堆vs数据段vs堆栈分配
我正在看下面的程序,不确定内存是如何分配的以及为什么:
void function() {
char text1[] = "SomeText";
char* text2 = "Some Text";
char *text = (char*) malloc(strlen("Some Text") + 1 );
}
在上面的代码中,最后一个显然是在堆中。 但是,据我了解,text2在程序的数据段中,而text1可能在堆栈中。 或者我的假设是错误的? 这里有什么正确的假设? 这个编译器是否依赖?
谢谢
// 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 );
是的,在大多数系统中,你是对的:
text1
将成为堆栈上的可写变量数组(它必须是可写数组)
text2
实际上必须是const char*
,并且是的,它会指向可执行文件的文本段(但可能会跨可执行格式更改)
text
将在堆上