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