Search code examples
cstringcstringstring-literals

Memory allocated in char * var; declaration


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?


Solution

  • 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.