0

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);
    }
    }
}
2
  • which struct error? Can you also add the valgrind output? Commented Dec 10, 2011 at 7:31
  • Can you paste the definition of the struct record? Commented Dec 10, 2011 at 7:51

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

sizeof(struct record *)? Should be sizeof(struct record) or sizeof(**array).
if you meant like here - stackoverflow.com/q/8460874/1090944, didn't work.
@AusCBloke sizeof(struct record *) means allocation memory in size of pointer to struct record.
@user1090944: I thought you asked for "Allocating dynamic array of struct ", not allocating an array of pointers to struct. And *array is of type struct record*, therefore the elements it's pointing to should be of type struct record and not struct record*.

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.