- 论坛徽章:
- 0
|
E*的问题出来了,我觉得他是对的.
看看代码吧:
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct linktype_s
- {
- int n;
- struct linktype_s * next;
- }LINKTYPE;
- int main()
- {
- linktype_s* link = (linktype_s *) malloc(sizeof(linktype_s));
- link->n = 1;
- link->next = NULL;
- long *p = (long*)((char*)(link) + sizeof(linktype_s) - sizeof(long*));
- printf("address of p \'p\': %p\n", p);
- printf("address of link->next: %p\n", &link->next);
- printf("content of link->next: %p\n", link->next);
- return 0;
- }
复制代码
程序运行的结果显示, 第一个和第二个输出结果是一样的,也就是说p的值实际上是next的地址,那么你的这段代码就有问题了:
- next=(char*)link+(nodesize-sizeof(long*));
- free(link);
- link=(void*)(*((long*)next));
复制代码
首先next存放的是link中next的地址,free(link)之后这个地址失效,所以最后一句解引用可能就会出错,当然运气好的话不会segmentation fault.
我想正确的顺序应该是这样:
- next=(char*)link+(nodesize-sizeof(long*));
- void* p = (void*)(*((long*)next));
- free(link);
- link= p;
复制代码
也就是说在free之前保存这个next指针的值. |
|