Subject: Re: A *really* off question
To: John A. Maier <>
From: Jeff Roberson <>
List: tech-pkg
Date: 01/05/2000 13:15:56
On Wed, 5 Jan 2000, John A. Maier wrote:

> #include <stdlib.h>
> #include <iostream.h>
> class testalloc {
> public:
> 	// This is my structure
> 	typedef struct {
> 		int rndnum1;
> 		int rndnum2;
> 	} STUFF;
> 	// create a variable of type STUFF
> 	STUFF rndtest[1];

To begin with, this should be a pointer to an array of STUFF, not just
STUFF.  Realloc only works on pointers allocated by malloc/calloc etc.
The results when used with any other pointer are unpredictable acording to
the man page. I usually calloc with a known initial number of elements,
and then keep track of the free elements with another variable.  Then when
you would like to add another element check the number of free elements,
and grow as apropriate while keeping track of the size with a variable.
For intsance:

int nelem = 5;
int nfree = 5;
STUFF *stufp;

stfup = calloc(nelem, sizeof(STUFF));

Ten to add you do the following:
if (nfree == 0) {
	nelem *= 2;
	stufp = realloc(stufp, sizeof(STUFF) * nelem);

And add your entries.

I hope this helps.  Keep in mind I didn't try to run the example code I
just gave, but it should work properly.