Reputation: 101
i have the following code, which should allocate a 2d array of width and height imageWidth using calloc (it's for a toy quadtree building program as it happens). the third debug print is to keep track of what happens in the arrays at image[0] through [10] as the loop progresses.
/* 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]);
}
when image width is smaller than ~20 (say 16), i get the expected prints, something like
0 0 0
1 0 0
2 0 0
etc...
15 0 0
but setting imageWidth to 29 gives something like
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
what could be causing this? i highly doubt that calloc would change the values in other memory when it is called again, so the error must be in my code. if its helpful, the two if statements simply lead to a puts() and exit(). they are not entered when i get the strange results.
thanks!
Upvotes: 0
Views: 114
Reputation: 141628
The first allocation should be:
char** image = calloc (imageWidth, sizeof *image);
because you are allocating "imageWidth" number of pointers, not that number of bytes.
Upvotes: 4