Reputation: 19
char *p = "hello";
p = "hello_2";
Here string "hello" was stored in memory and its address was present in pointer 'p' but when this pointer starts pointing to string "hello_2", what will happen to the memory where the string "hello" was stored? Will it be freed or this string remains there but we can't access it?
Upvotes: 1
Views: 85
Reputation: 19
There are different memory sections to which the globals, heap, code and string literals go to. It is specific to the compiler used.
gcc makes a .rodata section which is a read-only section and the string literals are stored there.
Visual C++ creates a .rdata section for the read only section.
You can use objdump (on linux) to check different sections for your binary.
Upvotes: 0
Reputation: 34588
You are actually creating a string literal named "hello"
allocating it somewhere in the memory , and assigning the address of first character of the literal to the pointer p
, and as the pointer is not constant you can assign it again with different addresses. And one more important point to note is that the string literal created are in read only memory.
Upvotes: 1
Reputation: 19864
What you have is a string constant and it is stored in read-only memory.
So this memory is not required to be freed explicitly using free()
Till the lifetime of the variable p
is valid you can access the stored string.
Upvotes: 2
Reputation: 13073
The memory will not be freed. But would not (in this case), be lost. The code knows where the string is, and uses it each time the fragment is run, to assign to the pointer p.
Memory which is on the heap does need to be freed (result of malloc
or strdup
).
Memory which is on the stack does not need to be freed.
Upvotes: 1