In C, declaring a char pointer like this
char* p="Hello";
allocates some memory for a string literal Hello\0
. When I do this afterwards
p="FTW";
what happens to the memory allocated to Hello\0
? Is the address p points to changed?
In C, declaring a char pointer like this
char* p="Hello";
allocates some memory for a string literal Hello\0
. When I do this afterwards
p="FTW";
what happens to the memory allocated to Hello\0
? Is the address p points to changed?
There is no dynamic memory allocation in either statement.
Those strings are stored in your executable, loaded in a (likely read-only) section of memory that will live as long as your process does.
The second assignment only changes what p
points to. Nothing else happens.
The memory remains occupied by "Hello"
. It is lost (unless you have other references to it).
The address p
is pointing to (the value of p
) is changed of course.
In this case, "Hello" is created at compile time and is part of the binary. In most situation "Hello" is stored in read only memory. "FTW" is also part of the binary. Second assignment will only change the pointer.
in addition - "Hello"
and "FTW"
have static storge duration as Met have pointed out
It creates a string constant that cannot be modified and should be used as it is.
If you try doing
p[0]='m';
It would give segmentation fault since this is not string literal with allocated memory in which you can reassign and read back values.
what if
p = getbuffer();
getbuffer()
{
return buf = malloc(buf, size);
}
how can free this memory before allocating new memory to p! imagine that p should use getbuffer() many times.