2011-06-01 156 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將在堆上