Reputation: 197
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.
Upvotes: 6
Views: 2920
Reputation: 471209
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
.
Upvotes: 6