反复调用 calloc 似乎会破坏早期调用的数据

calling calloc repeatedly seems to corrupt data from earlier calls

我有以下代码,它应该使用 calloc 分配一个宽度和高度为 imageWidth 的二维数组(它恰好用于玩具四叉树构建程序)。第三个调试输出是跟踪在循环过程中 image[0] 到 [10] 数组中发生的事情。

/* allocate pointer array memory */
char** image = calloc (imageWidth, 1);
if (image == NULL) errMalloc();

/* fill with a series of char arrays */
for (i = 0; i < imageWidth; i++) {
    image[i] = calloc (imageWidth, 1);
    if (image[i] == NULL) errMalloc();

    /* debug prints */
    printf("%d ", i);
    printf("%d ", image[i][0]);
    printf("%d\n", image[i%10][0]);
}

当图像宽度小于 ~20(例如 16)时,我得到预期的打印效果,例如

0 0 0
1 0 0 
2 0 0 
etc...
15 0 0

但是将 imageWidth 设置为 29 会得到类似于

0 0 0
1 0 0 
etc...
9 0 0 
10 0 16 //value at image [0][0] has changed
11 0 0 
etc...
19 0 0 
20 0 16
21 0 -96 // now value at image[1][0] has changed
22 0 0
etc..
27 0 0 
28 0 0 

这可能是什么原因造成的?我非常怀疑 calloc 在再次调用时会改变其他内存中的值,所以错误一定在我的代码中。 如果有用的话,这两个 if 语句只会导致 puts() 和 exit()。当我得到奇怪的结果时,他们没有输入。

谢谢!

第一次分配应该是:

char** image = calloc (imageWidth, sizeof *image);

因为您正在分配 "imageWidth" 个指针,而不是那个字节数。