Reputation: 13
Here I am copying the structure from one node to another but when I encounter the last node I will have a segmentation fault since temp_clsf->next
in memcpy
will be pointing to a invalid location, how can I fix this? I cant free temp_clsf
as it is not dynamic allocation.
while(temp_clsf!=NULL)
{
memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));
if(temp_clsf->next ==NULL)
return;
else
temp_clsf = temp_clsf->next;
}
Upvotes: 0
Views: 789
Reputation: 108968
Inside the loop, keep a pointer to the previous node. When the loop ends, update that node with a pointer to NULL
/* pseudo-code */
while () {
prev = curr;
/* ... */
}
prev->next = NULL;
Upvotes: 1
Reputation: 263469
It looks like you are doing a shift of items, potentially to remove one. If this was an ordered array, there would be no need to use a next
pointer. I'm not sure what other static allocation you are using, but you can simply do the following to remove the single item temp_clsf->next
:
temp_clsf->next=temp_clsf->next->next;
Upvotes: 0
Reputation: 4431
Potentially, temp_clsf->next
could be NULL
so move the NULL
check before the memcpy
while(temp_clsf != NULL)
{
if(temp_clsf->next == NULL)
{
return;
}
memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));
temp_clsf = temp_clsf->next;
}
Update: temp_clsf
and temp_clsf->next
look like pointers to me. So your memcpy
is taking address of pointers and overwriting what is there. Is this your intention? Not sure what sizeof(struct classifier)
is as we do not have the structure types in your example.
Upvotes: 0
Reputation: 108968
Just move the copy after the if
...
while(temp_clsf!=NULL)
{
if(temp_clsf->next ==NULL)
return;
//else
memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));
temp_clsf = temp_clsf->next;
}
Upvotes: 0