Search code examples
cstructsegmentation-faultdynamic-allocation

SegFault in dynamically allocated array of structs, C


typedef struct {
  double x;
  double y;
  long out_x;
  long out_y;
} coords;

typedef struct {
  char name[FIGURE_LEN + 1];
  int coordcount, size_tracker;
  coords *coordinate;
} fig;

fig figure;
fig * figpoint;

this is the functions that are being called from the parser.c source file.

void initialize_fig(int n, char * name, double x, double y,
                         fig *fig_point)
{
  printf("inside function\n");
  strncpy(fig_point[n].name, name, FIGURE_LEN + 1);
  fig_point[n].size_tracker = 1;
  fig_point[n].coordinate = malloc(sizeof(coords) * fig_point[n].size_tracker);
  assert(fig_point[n].coordinate != NULL);
  fig_point[n].coordcount = 0;
  fig_point[n].coordinate[fig_point[n].coordcount].x = x;
  fig_point[n].coordinate[fig_point[n].coordcount].y = y;
}

void create_FigArray(fig * fig_point, int fig_size)
{
  fig_point = malloc(sizeof(fig) * fig_size);
  assert(fig_point != NULL);
  fig_point = &figure
}

i first call create_FigArray like so...

create_FigArray(fig_point, 16);

i get no seg fault here... but then i call...

initialize_fig(0, Qe, 10.0000, 10.0000, fig_point);

the parameters are actually passed through variables but i just wanted to show that they are proper parameters and give an example of what values are passed. Anyways it hits

strncpy(fig_point[n].name, name, FIGURE_LEN + 1);

and stops.. segfault must happen here, but why?!

please help, explain and show how to get around this. thank you.


Solution

  • You allocate memory, then you change the pointer

    fig_point = malloc(sizeof(fig) * fig_size); // allocate here
    assert(fig_point != NULL);
    fig_point = &figure;  // now you make fig_point point to something else
    

    therefore your fig_point pointer no longer points to your dynamically allocated memory. If you then do this

    fig_point[n]
    

    you are accessing memory out or range since figure is not an array. In addition you pass the pointer fig_point to create_FigArray directly. This will create a copy of the pointer and hence any changes you make to that argument are in fact only changes to the copy. This means that the dynamic memory you that the address stored in fig_array after create_FigArray has returned is the same as it was before - it is only the copy that was changed by the function. If you want to change the pointer you need to use a double pointer argument to the function and then something like

    void create_FigArray(fig** fig_point, int fig_size)
    {
        *fig_point = malloc(sizeof(fig) * fig_size);
    }