setting elements of a structure to random double values using an array of pointers to the structure

Viewed 47

I am trying to make an array of pointers to a structure the program runs, however it just says 'Segmentation fault: 11' any help would be be very much appreciated

typedef struct
{
  int id;
  double x;
  double y;
  char name[30];
  int named;
} Star;


Star *stars[10];


int bang (int n_stars)
{
  if ((n_stars >= 1) && (n_stars <= 10))
{
    for (int i = 0; i < n_stars; i++)
    {
      double x = rand() % 10;
      double y = rand() % 10;
      stars[i] = (Star*) malloc(sizeof(x) + sizeof(y));
      stars[i]->x = x;
      stars[i]->y = y;
      free(stars[i]);
      return 1;
    }
}
else
{
    return 0;
}
return 0;
}
1 Answers

For the sake of the argument, let us disregard struct alignment and assume a target (such as x86) where:

sizeof(double) == 8, and sizeof(int) == 4.

Now, you're allocating a block of memory 16 bytes in size:

stars[i] = (Star*) malloc(sizeof(x) + sizeof(y));

The definition of the struct is:

typedef struct
{
  int id;
  double x;
  double y;
  char name[30];
  int named;
} Star;

Note the offset of y is 12 bytes. When you perform:

stars[i]->y = y;

The value of y is written to the address &stars[i] + 12 bytes. Double taking up 8 bytes, this will overflow your allocation (12+8 > 16), mentioned above.

You most likely want to change the allication to stars[i] = malloc(sizeof(Star));, to allocate the proper amount of space for your struct.

EDIT: If you are planning to use the allocated data elsewhere, you should remove the call to free, and instead free the data after you are done with it in your program. The return statement on the following line may possibly be a mistake too, as it exits the loop on the first iteration, which is most likely not what you want.

Related