You should program as if the old pointer is overwritten, yes. The old memory is no longer allocated so can be re-allocated by another part of your program (or a system thread for example) and written over at any time after you call realloc.
The new memory will always contain the same data that was present in the old memory though (it is copied for you if necessary), but only up to the size of the old block, any extra space allocated at the end will be uninitialised.
If you want a copy then do a new malloc and use memcpy.
Implementation-wise, when you call realloc to increase the size, one of these things might happen:
- A new block is allocated and the contents of the old memory copied, the old block is freed, the new pointer is returned.
- If the area after the block is not allocated, the existing block may be extended and the same pointer returned.
Since you have no way of knowing which has happened, or even if a completely different implementation to that suggested above is used, you should always code according to the spec of realloc, which is that you must not use the old pointer any more and you must use the new one.
oldpointer = newpointer;
shouldnewpointer
be freed or I must keep it? – Indiraindirect