2011-06-01 92 views
11

在看下面的程序并不能确保内存的分配方式和原因:堆VS数据段VS堆栈分配

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

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

感谢

+1

+1:非常符合问题 – Heisenbug 2011-06-01 16:57:15

+0

您是否了解指针与它指向的数据之间的区别? – n0rd 2011-06-01 17:09:17

+0

是的n0rd,但是这一个打击我,因为它似乎有这样一个有多个可能的选择.. – Kiran 2011-06-01 17:47:56

回答

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

如果你抛弃了'text2'的常量并尝试修改它会发生什么?这是段错误吗? – 2014-02-18 20:54:24

+0

是的。这会导致段错误。 – Jagannath 2017-01-19 06:12:50

+1

@DrewNoakes它是未定义的行为。它可能是段错误,但你不能指望它。 – 2017-02-02 18:57:50

5

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

text1将在堆栈可写数组变量(它需要一个可以写入阵列)

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

text将在堆上