Allocating dynamic array of struct on C. Valgrind found this error: Use of uninitialised value of size 8. The error pops up while trying to access the struct member.
What is the way to avoid that?
void find_rate()
{
int num_lines = 0;
FILE * in;
struct record ** data_array;
double * distance;
struct record user_record;
in = open_file();
num_lines = count_lines(in);
allocate_struct_array(data_array, num_lines);
data_array[0]->community_name[0] = 'h'; // the error is here
printf("%c\n", data_array[0]->community_name[0]);
fclose(in);
}
FILE * open_file()
{
..... some code to open file
return f;
}
int count_lines(FILE * f)
{
.... counting lines in file
return lines;
}
Here is the way I allocate the array:
void allocate_struct_array(struct record ** array, int length)
{
int i;
array = malloc(length * sizeof(struct record *));
if (!array)
{
fprintf(stderr, "Could not allocate the array of struct record *\n");
exit(1);
}
for (i = 0; i < length; i++)
{
array[i] = malloc( sizeof(struct record) );
if (!array[i])
{
fprintf(stderr, "Could not allocate array[%d]\n", i);
exit(1);
}
}
}
Since you are passing the address of array to the function allocate_struct_array
You need:
*array = malloc(length * sizeof(struct record *));
And in the calling function you need to declare data_array
as:
struct record * data_array;
and pass its address as:
allocate_struct_array(&data_array, num_lines);
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.