A C program with code typified by the following pared-down example
has been running after compilation on numerous compilers for several
years. However with a fairly recent GCC compiler it results in a
segmentation fault at the indicated instruction.
Briefly, the problem occurs when writing to an array element when
the array pointer is allocated by a function in the array index.
My question: Is this bad C code, "unwise" C code, or a compiler bug?
(Note: This simple example is obviously not production code.)
Thanks for your help.
Regards,
Charles Sullivan
-----------------------------------------
#include <stdio.h>
#include <stdlib.h>
int nextindex ( int **arrayp )
{
static int lastindex = -1;
if ( *arrayp == NULL )
*arrayp = calloc(100, sizeof(int));
return ++lastindex;
}
int main ( void )
{
int j;
int *array = NULL;
for ( j = 0; j < 10; j++ )
array[nextindex(&arra y)] = 10 * j; /* segfaults */
for ( j = 0; j < 5; j++ )
printf("array[%d] = %d\n", j, array[j]);
return 0;
}
--------------------------------------
Comment