THINK C calloc() quirk
William H Hsu
hsu_wh at jhunix.HCF.JHU.EDU
Tue Jul 24 00:55:43 AEST 1990
I have encountered a very elusive calloc() quirk which did not
appear when I first developed my project on a UNIX C system. Below is what
I believe is the offending block, dropped into a new test file:
#include <stdio.h>
#define UNIT 100
typedef int **MATRIX;
void main()
{
int i, size=20;
MATRIX table;
if (table = (MATRIX)calloc(size, sizeof(int *)))
{
for (i = 0; i < size; i++)
{
table[i] = (int *)calloc(2, sizeof(int));
table[i][0] = UNIT*i;
printf("### %d\t%d\t%d\n", i, UNIT*i, table[i][0]);
}
}
}
This block gave no trouble on the UNIX system and came straight from
Kernighan and Ritchie and Kelley and Pohl's suggested methods for dynamic
allocation of a 2-D array. I have successfully removed the segment to
another function in the "real" program (using triple indirection). The Mac
doesn't complain at all until runtime, when it reaches the printf statement.
In the above version, it apparently skips out of the for loop completely;
other versions where usage of the calloc'ed array is attempted induce a bomb
(frozen mouse, etc.) - worse still, some versions only bomb on the first
run! Commenting-out the printf statements seems to prevent a crash, but of
course, leaves me blind as to the results of the allocation. I am fairly
certain that the second calloc (the one in the loop) is the bad one, and
putting an "if (! table[i] .... ))" in the loop seems to verify this.
My question: why would this very standard array allocation work
perfectly on a mainframe, but crash spectacularly when ported to a
Macintosh? The differences in "int" (size 4 on the UNIX machine and 2 on
the Mac) and "int **" (both size 4 bytes) don't seem to make a difference.
Could someone suggest a more universal allocation scheme, one which would
run on either system?
Please E-mail responses to: hsu_wh at jhunix.hcf.jhu.edu (BITNET)
hsu at cs.jhu.edu (APRAnet)
More information about the Comp.lang.c
mailing list