简体   繁体   中英

heap vs data segment vs stack allocation

Am looking at the following program and not sure how the memory is allocated and why:

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

In the above code, the last one is obviously in the heap. However, as I understand text2 is in the data segment of the program and text1 may be on the stack. Or is my assumption wrong? What is the right assumption here? Is this compiler dependent?

// 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 );

Yes you are right, on most systems:

text1 will be a writable variable array on stack (it is required to be a writable array)

text2 has to be const char* actually, and yes, it will point to a text segment of the executable (but that might change across executable formats)

text will be on heap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM