Here I am copying the structure from one n开发者_开发知识库ode 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;
}
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;
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;
}
use following condition in while.
while(temp_clsf->next!=NULL)
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.
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;
精彩评论