When we reallocate memory via realloc()
, are the previous contents over-written? I am trying to make a program which reallocates memory each time we enter the d
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:
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.