#include <stdio.h>
#include <stdlib.h>
typedef struct lis
{
int num;
struct lis * next;
} list;
void fun(list ** h, int nu) {
*h = malloc(sizeof(list)*nu);
list *p = *h;
int i=1;
list * nextx;
while(i<=nu) {
nextx = p + 1;
p->num = i;
p->next = nextx;
//printf("%d\n", nextx);
p += 1;
i++;
}
p->next = NULL;
}
int main(int argc, char const *argv[])
{
list * first = NULL;
fun(&first,10);
free(first);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在学习c中的列表
无论何时运行此代码,都会产生malloc错误
如果我注释掉printf("%d\n", nextx);哪个显示下一个节点就可以了.
怎么了?
在循环的最后一次运行中,您的代码执行:
nextx = p+1; // points one past the last array' element
p->num = nu-1; // ok
p->next = p+1; // probably not what you wanted, but not a fault per se
p += 1; // This is the cause of your problem
i++; // out of the loop...
p->next = NULL; // dereference out of array pointer!
Run Code Online (Sandbox Code Playgroud)
退出循环前一步,然后正确设置最后一个元素:
while (i<nu) {
...
}
p->next = NULL;
p->num = nu-1;
Run Code Online (Sandbox Code Playgroud)