The task of deallocating memory is imposed on the owner of that memory. Just because you have a pointer to some memory region does not mean that you own that memory and, therefore, does not mean that you are responsible for deallocating it.
String literal "hello world"
is an object with static storage duration. It is stored in static memory. Static memory is always owned by the runtime environment. The runtime environment is aware of data stored in static memory. The runtime environment knows when that data has to be deallocated (which is easy, since static memory is basically "never" deallocated - it exists as long as your program runs).
So, again, you with your pointer p
do not really own any memory in static region. You just happen to refer to that memory with your p
. It is not your business to worry about deallocation of that memory. It will be properly deallocated when the time comes (i.e. when the program ends) and it will be done properly without any help from you and your pointer p
. You can change your p
as much as you want, you can make it point to a completely different memory location, or you can discard it without any reservations. Speaking informally, nobody cares about your p
.
The only memory you can possibly own in a C program is memory you personally allocated with malloc
(or other dynamic memory allocation functions). So, you have to remember to eventually call free
for the memory that you allocated yourself (and you have to make sure you know the original value returned by malloc
to pass to that free
). All other kinds of memory (like static or automatic) are never owned by you, meaning that freeing it is not your business and preserving the original pointer values is completely unnecessary.