Pointer to a Pointer to a Structure and malloc memory for array

Go To StackoverFlow.com

2

I'm creating a pointer to a pointer to a structure to create a dynamic array with malloc in C, but I get a segmentation fault calling the struct array. Here is a quick rundown of my code:

#include <stdio.h>

typedef struct {
    int test1;
    int test2;
    }testStruct;

int main() {
    testStruct **neato;

    neato = (testStruct **) malloc( sizeof(testStruct *) * 5);
    // Array of 5 for convience

    // any neato[x]->testy call results in segmentation fault.
    scanf("%d", &neato[0]->test1);    // Segmentation fault

    return 0;
    }

I tried other calls like (*neato)[0].test1 and all result in segmentation fault. This is obviously not the proper way to do this or my GNU compiler is seriously outdated.

2012-04-05 02:38
by T.Jones
Do not cast the return value of malloc. See: http://c-faq.com/malloc/mallocnocast.htm - Matt Eckert 2012-04-05 02:44


5

You've allocated enough memory for 5 pointers. You have not however initialized the pointers, so they are garbage. Allocate the pointers and then proceed to initialize each pointer.

int elems = 5;

neato = malloc(sizeof(testStruct *) * elems);
for( i = 0; i < elems; ++i ) {
    neato[i] = malloc(sizeof(testStruct));
}

On a side note, I don't see a need for an array of pointers here. Why not simply allocate enough space for 5 testStructs (i.e., neato becomes a testStruct*) and pass the address of that pointer to the function that initializes it?

2012-04-05 02:40
by Ed S.
D'oh! Went straight over my head. Thanks for your help - T.Jones 2012-04-05 02:50


0

you aren't mallocing space for all the structures themselves you have to add

for(int i = 0; i < 5; i++) {
    neato[i] = malloc(sizeof(testStruct));
}

After you malloc neato. Also you should check your return value from malloc for NULL to make sure malloc passed.

2012-04-05 02:41
by twain249
No need to cast the result of malloc in C - Ed S. 2012-04-05 02:42
@EdS. True but it doesn't hurt - twain249 2012-04-05 02:44
It can actually. It's just totally unnecessary, serving only to add verbosity to your code, and it can actually be bad in a more meaningful way. See: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-mallo - Ed S. 2012-04-05 02:44
Ok I'll remove it - twain249 2012-04-05 02:45


0

You allocated array of pointers, but did not assign valid address to these pointers.

If you only want to create dynamic array, use just pointer to the struct:

testStruct *neato;
neato = malloc( sizeof(testStruct) * 5);
scanf("%d", &neato[0].test1);
2012-04-05 02:42
by asaelr
Ads