c - 重新分配后如何将新内存清零

标签 c null memory-management

调用 realloc 后将新内存清零同时保持初始分配的内存完好无损的最佳方法是什么?

#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

size_t COLORCOUNT = 4;

typedef struct rgb_t {
    int r;
    int g;
    int b;
} rgb_t;

rgb_t** colors;

void addColor(size_t i, int r, int g, int b) {
    rgb_t* color;
    if (i >= COLORCOUNT) {
        // new memory wont be NULL
        colors = realloc(colors, sizeof(rgb_t*) * i);
       //something messy like this...
        //memset(colors[COLORCOUNT-1],0 ,sizeof(rgb_t*) * (i - COLORCOUNT - 1));

         // ...or just do this (EDIT)
        for (j=COLORCOUNT; j<i; j++) {
            colors[j] = NULL;
        }

        COLORCOUNT = i;
    }

    color = malloc(sizeof(rgb_t));
    color->r = r;
    color->g = g;
    color->b = b;

    colors[i] = color;
}

void freeColors() {
    size_t i;
    for (i=0; i<COLORCOUNT; i++) {
        printf("%x\n", colors[i]);
        // can't do this if memory isn't NULL
       // if (colors[i])
         //   free(colors[i]);

    }
}


int main() {
    colors = malloc(sizeof(rgb_t*) * COLORCOUNT);
    memset(colors,0,sizeof(rgb_t*) * COLORCOUNT);
    addColor(0, 255, 0, 0);
    addColor(3, 255, 255, 0);
    addColor(7, 0, 255, 0);


    freeColors();
    getchar();
}

最佳答案

作为一般模式,没有办法解决这个问题。原因是为了知道缓冲区的哪一部分是新的,您需要知道旧缓冲区的长度。在 C 中无法确定这一点,因此无法获得通用解决方案。

但是你可以像这样写一个包装器

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

关于c - 重新分配后如何将新内存清零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58876339/

相关文章:

objective-c - UIButton 触摸后保留计数器增加

c - C语言预处理分析

当 .exe 在 Windows 7 32 位上运行时,使用 GCC 编译的 C 程序会导致 NVTDM 错误

java - 从 Java ResultSet 检查 null int 值

kotlin - 在null引用上调用扩展函数时,没有NullPointerException

ruby-on-rails - 不将 nil 值分配给哈希

cocoa-touch - iOS 应用程序启动时占用近 40mb

c - setjmp/longjmp 失败

c - 在 Linux 中查找链接到二进制文件的 SQLite 版本

c# - 即使此 Func<> 变量为空,是什么导致内存分配?