pointer allocation

Wade Guthrie evil at arcturus.UUCP
Wed Dec 21 04:03:36 AEST 1988


You found yourself a stray pointer!

In article <8Xf3eSy00UkZ40cVE0 at andrew.cmu.edu>, xj01+ at andrew.cmu.edu (Xue Jue) writes:

> #include <stdio.h>
> int *(*B);

what you're doing here, is setting B up to be a pointer to a pointer to an int
so let's look at a <REALLY> simple model for what is going on in memory:

	variable	type			address		contents

	B		pointer to pointer	good1		garbage1
	(*B)		pointer to int		garbage1	garbage2
	(**B)		int			garbage2	garbage3

> main()
> {

Just an aside, you might declare calloc to return a pointer rather than
an int (default):
	char * calloc();	/* this'll help */

>	*B = (int *) calloc(18,sizeof(int));

When you do this, calloc allocates space for 18 ints somewhere in memory,
and passes this back to the thing to which B points.  Let's look at this
in two steps: 1) calloc allocates space for 18 ints

	variable	type			address		contents

	B		pointer to pointer	good1		garbage1
	(*B)		pointer to int		garbage1	garbage2
	(**B)		int			garbage2	garbage3

	(none)		int (18 of them)	good2		garbage4

And put that address (good2, in this case) into the thing to which B points:

	variable	type			address		contents

	B		pointer to pointer	good1		garbage1
	(*B)		pointer to int		garbage1	good2

	(**B)		int (18 of them)	good2		garbage4
> }

What you have succeeded in doing is putting an address at a garbage value
in memory (the address garbage1).  You need first to assign B to point to
something for which space has been allocated.  I find that memory maps
like these help to sort out what is going on.  The segmentation fault was
when you put something (in this case, the address good2) into a location
which was out of the legally addressable memory 

> By the way, this is on IBM RT work station. The same thing has been 
> running on IBM PC with microsoft C 5.0.

Maybe the IBM RT initializes variables to zero, making garbage1 actually 
NULL, and doesn't allow dereferencing a NULL pointer (a very wise practice, 
since it is non portable).  The IBM PC does not set variables to zero, so 
you were really corrupting the heap.  If your program was small, chances 
are that you would not see the error.  If this same program grew to the 
point where you were corrupting data and/or code, then the debugging job 
would be monsterous (because the bug would have been there since God 
invented dirt, but the places to look for bugs are the most recently 
written routines).
 

Wade Guthrie
Rockwell International
Anaheim, CA

(Rockwell doesn't necessarily believe / stand by what I'm saying; how could
they when *I* don't even know what I'm talking about???)



More information about the Comp.lang.c mailing list