gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:15 24 4
gpt4 key购买 nike

我有以下代码,它应该使用 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”指针数,而不是字节数。

关于反复调用 calloc 似乎会破坏早期调用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com