15

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

void function() {
    char text1[] = "SomeText";
    const char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}

在上面的代码中,最后一个显然是在堆中。但是,据我了解text2,它位于程序的数据段中,并且text1可能位于堆栈中。还是我的假设是错误的?这里正确的假设是什么?这个编译器依赖吗?

4

2 回答 2

18
// 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 );
于 2011-06-01T17:07:29.993 回答
5

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

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

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

text将在堆上

于 2011-06-01T17:08:09.177 回答