# Thread: allocating memory for structure

1. ## allocating memory for structure

hi, i have a simple question and would apprichiate if someone could give me a detailed explanation. so what i have is a structure like this:

Code:

typedef struct tuple{
int x;
struct tuple *childTuple;
}Tuple;
and the code that follows look like this:
Code:
int ntop = -1;

void fpush (Tuple *newTuple, Tuple **top,int topSize){
if ( ntop== topSize){
printf( "stack overflow");
return;
}
ntop++;
top[ntop] = newTuple;
}

int main(){
Tuple *lastInterval = (Tuple *)malloc(100*sizeof(Tuple));
Tuple **top = (Tuple **)malloc(sizeof(Tuple *));
top[0] =(Tuple *)malloc(sizeof(Tuple));
top[0]->childTuple = (Tuple *)malloc(100*sizeof(Tuple));
lastInterval = NULL;
top[0] = NULL;

for (i=0;i<=100;i++){
lastInterval = fcreateTup(i,i+1,i+2,lastInterval);
fpush(lastInterval,top,200);
}

}
so my question now is : do i need to allocate 100 times Tuple for:

Code:
Tuple **top = (Tuple **)malloc(sizeof(Tuple *));
top[0] =(Tuple *)malloc(sizeof(Tuple));
or not , because it seams to work both ways. and why does it work if it works and it is not just my imagination ?

cheers

baxy

2. I'm not really clear on what your code is trying to do, and you don't show us fcreateTup. I'm guessing your after something like a 2-d array, but dynamically allocated. See if this link helps: Question 6.16. Otherwise, you will have to do lots more explaining.

3. > Tuple **top = (Tuple **)malloc(sizeof(Tuple *));
You should avoid casting the return result of malloc (see the FAQ).

Also, if you write malloc calls in this form, there is minimal chance of screwing things up.
p = malloc( numNeeded * sizeof(*p) );

So for example
Tuple **top = malloc(sizeof(*top));

Code:
top[0] =(Tuple *)malloc(sizeof(Tuple));
top[0]->childTuple = (Tuple *)malloc(100*sizeof(Tuple));
lastInterval = NULL;
top[0] = NULL;
This just leaked some memory.
It'll also cause a segfault if you try and use top[0] now for something.

Popular pages Recent additions