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.
There is another way to make an array of struct in C. The memory can be allocated using the malloc() function for an array of struct . This is called dynamic memory allocation. The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size.
To allocate a new person in the myperson argument, we use the following syntax: person * myperson = (person *) malloc(sizeof(person)); This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory and then return a pointer of type person to the newly allocated data.
Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).
Dynamic memory allocation allocates memory on the heap as needed at run time, instead of allocating memory statically on the stack. Dynamic memory allocation is beneficial when: You do not know the upper bound of an array. You do not want to allocate memory on the stack for large arrays.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With