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.
You allocate memory, then you change the pointer
therefore your
fig_pointpointer no longer points to your dynamically allocated memory. If you then do thisyou are accessing memory out or range since
figureis not an array. In addition you pass the pointerfig_pointtocreate_FigArraydirectly. This will create a copy of the pointer and hence any changes you make to that argument are in fact only changes to thecopy. This means that the dynamic memory you that the address stored infig_arrayaftercreate_FigArrayhas returned is the same as it was before – it is only thecopythat 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