6

I've found useful answers on other people's questions countless times here on stackoverflow, but this is my first time asking a question of my own.

I have a C function that dynamically needs to allocate space for an array of structs and then fill the struct members of each array element with values pulled from a file. The member assignment works fine on the first pass of the loop, but I get a segmentation fault on the second pass.

I've written up this quick program illustrating the essentials of the problem I'm having:

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

typedef struct {
        int a;
        int b;
} myStruct;

void getData(int* count, myStruct** data) {
    *count = 5;
    *data = malloc(*count * sizeof(myStruct));

    int i;
    for (i = 0; i < *count; i++) {
        data[i]->a = i;
        data[i]->b = i * 2;
        printf("%d.a: %d\n", i, data[i]->a);
        printf("%d.b: %d\n", i, data[i]->b);
    }
}

int main() {
    int count;
    myStruct* data;
    getData(&count, &data);
    return 0;
}

The output I get from this is:

0.a: 0
0.b: 0
Segmentation fault

I'm not sure where my problem lies. It seems as though the malloc call is only allocating enough space for one struct when it should be allocating space for five.

Any help would be very much appreciated.

1 Answer 1

6

The error is here:

for (i = 0; i < *count; i++) {
    data[i]->a = i;
    data[i]->b = i * 2;
    printf("%d.a: %d\n", i, data[i]->a);
    printf("%d.b: %d\n", i, data[i]->b);
}

you should do this:

for (i = 0; i < *count; i++) {
    (*data)[i].a = i;
    (*data)[i].b = i * 2;
    printf("%d.a: %d\n", i, (*data)[i].a);
    printf("%d.b: %d\n", i, (*data)[i].b);
}

The reason is that you are indexing the wrong "dimension" of data.

Sign up to request clarification or add additional context in comments.

3 Comments

You need to dereference data in the printfs too
Thanks for the incredibly quick response!
I would say not a "wrong dimension" of data but a wrong array at all. As data[i] literally means "get i-th element of array of (myStruct*) (pointers to myStruct)" and the size of each element is a size of the pointer. And (*data)[i] is "i-th element of the (*data) array which is an array of flat myStruct structures"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.