Search code examples
c++memory-leaksstring-literals

char* Space Allocation


My understanding is that in C and C++, creating a character array by calling:

char *s = "hello";

actually creates two objects: a read-only character array that is created in static space, meaning that it lives for the entire duration of the program, and a pointer to that memory. The pointer is a local variable to its scope then dies.

My question is what happens to the array when the pointer dies? If I execute the code above inside a function, does this mean I have a memory leak after I exit the function?


Solution

  • it lives for the entire duration of the program

    Exactly, formally it has static storage duration.

    what happens to the array when the pointer dies?

    Nothing.

    If I execute the code above inside a function, does this mean I have a memory leak after I exit the function?

    No, because of (1). (The array is only "freed" when the program exits.)