How to zero out new memory after realloc

前端 未结 4 1101
闹比i
闹比i 2020-12-06 10:53

What is the best way to zero out new memory after calling realloc while keeping the initially allocated memory intact?

#include 
#include <         


        
4条回答
  •  醉话见心
    2020-12-06 11:44

    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;
    }
    

提交回复
热议问题