I would like to try allocating my first 10 structs. We have to store an array of struct pointer at the heap but I don't know what i am doing wrong
my struct looks like this
typedef struct TEST
{
char* first_string;
char* second_string;
} test;
what i have written:
test **string_pair;
string_pair = malloc(10 * sizeof(test *));
if(string:pair == NULL)
{
free(string_pair);
exit(4);
}
This works fine However later I am trying in an for loop to allocate my strings
string_pair[count]->first_string = malloc(10 * sizeof(char)); // note that count is currently 0
if(string_pair[count]->first_string == NULL)
{
free(string_pair[count]->first_string);
free(string_pair[count]);
exit(4);
}
And I get an segmentation fault
Before anyone suggests we are not allowed to simply use an array of structs we have to do it the complicated way.
Thx in advance
You allocated an array of pointers.
But you did not allocate memory for the actual structures, and you did not initialize the pointers you allocated.
This line:
string_pair = malloc(10 * sizeof(test *));
Allocates array of 4 or 8 (depending on your architecture) byte variables that can store memory addresses.
It does not allocate struct TEST
. The pointers will contain garbage (possibly invalid) addresses until you initialize them.
You are suppose to do it by calling malloc
for struct TEST
, and placing the resulting pointer in the array.
Otherwise, when your code reaches this line:
string_pair[count]->first_string
it will look for struct TEST
at some random address, possibly 0, and try to read its first_string
field, which will cause segmentation fault.
You are getting a segmentation fault because you are allocating an array of pointers but not allocating the structure itself.
With string_pair = malloc(10 * sizeof(test *));
, you allocate string_pair
(a pointer to a pointer) to 10 pointers (pointing to a test
structure).
Then, with string_pair[count]->first_string = malloc(10 * sizeof(char));
, you allocate the first_string
member of string_pair[count]
to a string of 10 characters. The ->
token means to access the member in string_pair[count]
. However, the actual structure is not allocated.
You need to allocate string_pair[count]
, with something like string_pair[count] = malloc(sizeof(test));
.
I'd recommend just using a test*
for your array, and allocating it with test* string_pair = malloc(10 * sizeof(test));
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.