我创建了一个非常简单的链表,并注意到我的代码的tcc filename.c
vs输出有所不同:tcc filename.c -run
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct llist {
struct llist *next;
struct llist *last;
struct llist *first;
int value;
int item;
int *length;
};
struct llist *newList(int v){
struct llist *l1 = malloc(sizeof(struct llist));
l1 -> length = malloc(sizeof(int));
*l1 -> length = 1;
l1 -> value = v;
l1 -> item = 0;
l1 -> first = l1;
return l1;
}
struct llist *appendList(struct llist *l1, int v){
struct llist *l2 = malloc(sizeof(struct llist));
l2 -> value = v;
l2 -> last = l1;
l2 -> first = l1 -> first;
l2 -> length = l1 -> length;
*l2 -> length += 1;
l2 -> item = l1 -> item + 1;
l1 -> next = l2;
return l2;
};
int main(){
struct llist *list = newList(4);
list = appendList(list, 6);
list = appendList(list, 8);
list = appendList(list, 10);
list = list -> first;
int end = 0;
while(end==0){
printf("VAL: %d\n", list -> value);
if(list -> next == NULL){
printf("END\n");
end = 1;
}else{
list = list -> next;
}
}
return 0;
}
对于编译tcc filename.c
然后运行它会产生我期望的输出:
VAL: 4
VAL: 6
VAL: 8
VAL: 10
END
这也是我在 GCC 和 clang 中得到的输出。
当我使用时,tcc filename.c -run
我得到:
VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END
最后一个数字始终为零,而其他两个额外的值每次运行时都不同。
我想出了l1 -> next = NULL;
在newList
函数和函数l2 -> next = NULL;
中添加的解决方案appendList
。
但我想知道为什么输出会有所不同。编译器中是否存在错误,或者NULL
即使它在大多数编译器中都有效,但我没有初始化指针是错误的?