What is the best way to zero out new memory after calling realloc while keeping the initially allocated memory intact?
#include
#include <
There is no way to solve this as a general pattern. The reason why is that in order to know what part of the buffer is new you need to know how long the old buffer was. It's not possible to determine this in C and hence prevents a general solution.
However you could write a wrapper like so
void* realloc_zero(void* pBuffer, size_t oldSize, size_t newSize) {
void* pNew = realloc(pBuffer, newSize);
if ( newSize > oldSize && pNew ) {
size_t diff = newSize - oldSize;
void* pStart = ((char*)pNew) + oldSize;
memset(pStart, 0, diff);
}
return pNew;
}