2017-02-12 34 views
-1
#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; 
} 

我学习列表在C不使用printf()的

每当这个代码运行如果我注释掉printf("%d\n", nextx);这表明下一个节点它提供了一个malloc的错误

时,遇到了一个错误的malloc它工作正常。

发生了什么事?

+2

请张贴一个完整的例子。一定要显示所有的变量声明和初始化。同时显示你得到的确切的错误信息。 –

+1

如果添加/删除'printf()'语句会更改您是否遇到错误,则几乎总是表明您在程序的某处导致了未定义的行为。 UB并不总是触发一个错误,它只会破坏内存,然后取决于你以后做了什么,不管你是否遇到错误。 – Barmar

+0

你得到了什么确切的错误? – Barmar

回答

5

在循环的最后运行,你的代码做:

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! 

1步前退出循环,然后正确设置的最后一个元素:

while (i<nu) { 
    ... 
} 
p->next = NULL; 
p->num = nu-1;