Memory Allocation Problem

Andrew Brush Sverdrup smbrush at helios.lerc.nasa.gov
Wed Jan 30 02:38:19 AEST 1991


In response to Kevin Hill's question in 7156 at crash.cts.com,

I compiled and ran the following small program on my PC using MSC5.1
and on VMS using VAX C v3.0 with no problems.

#include <stdlib.h>
#include <stdio.h>

void main(void);

void main(void){
int **track;
int ix, iy;
track = (int **)malloc( (unsigned)(100*sizeof(int *)));
track[0] = (int *)malloc( (unsigned)(100*sizeof(int)));

for (ix=1;ix<100;ix++){
    track[ix] = track[ix-1] + (100*sizeof(int));
    printf("%p\n",track[ix]);
    }
for (ix=0;ix<100;ix++){
    for (iy=0;iy<100;iy++){
        track[ix][iy] = ix*iy;
        printf("%d\n",track[ix][iy]);
        }
    }
}


This is slightly different from his program fragment:

int	**track;
int	**map;
char	*bigmap;

int					cursor,x1 = 0,y1 = 0,gx,gy;
WindowPtr				thewind,thewind1;
WindowRecord			windowmemory,windowmemory1;
BitMap				themap1,store;
char					iconmap[128];
Rect					oldbox;
int					**track;
int					**map;
char					*bigmap;

Initialize()
{
	int	x,y;
	
	gx = gy = 0;
	
	
	store.rowBytes = 4;
	SetRect(&store.bounds,0,0,32,32);
	
	if ( (bigmap = (char *)( malloc( (unsigned)(100 * 100 * 128)) )) == NULL)
		ExitToShell();
	track = (int **)malloc( (unsigned)(100 * sizeof(int *)) );	
	
	track[0] = (int *)malloc( (unsigned)( 100 * 100 * sizeof(int)) );
	if (track[0] == NULL)
		ExitToShell();
		
	map = (int **)malloc( (unsigned)(100 * sizeof(int *)) );
	
	map[0] = (int *)malloc( (unsigned)(100 * 100 * sizeof(int)) );
	if (map[0] == NULL)
		ExitToShell();
	
	
	for (x = 1; x < 100; x++)
	{
		track[x] = track[x-1] + (100 * sizeof(int));
		map[x] = map[x-1] + (100 * sizeof(int));
		for (y = 0; y < 100; y++)
		{
			map[x][y] = -1;
			track[x][y] = -1;
		}
	}
}
}


1) For some reason, he shows declarations for his pointer variables
twice.

2) His attempt to initialize track and map while also organizing their
memory results in failure to initialize row [0] of them.

3) I'm not using any error checking on malloc, although i should. 
Kevin isn't using error checking when allocating memory for track or
map.  Possibly, the request for 1,280,000 bytes (or more, depending on
sizeof(char) ) for bigmap uses up his available memory, resulting in
track==NULL (which is untested), so an attempt to do: track[0]= ....
is an attempt to assign a value to something with the address of NULL.


Andy Brush [Sverdrup Technology] 216-826-6770
SMBRUSH at MARS.lerc.nasa.gov



More information about the Comp.lang.c mailing list