heap vs data segment vs stack allocation

前端 未结 2 1835
醉话见心
醉话见心 2021-02-05 12:35

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

void function() {
    char text1[] = \"SomeText\";
    char* text2 = \"Some         


        
2条回答
  •  旧巷少年郎
    2021-02-05 12:57

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

提交回复
热议问题