【发布时间】:2017-07-07 17:41:57
【问题描述】:
我创建了一个非常简单的链表,并注意到我的代码的 tcc filename.c 与 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
最后一个数字总是为零,而其他两个额外的值每次运行时都不同。
我想出了在newList 函数中添加l1 -> next = NULL; 并在appendList 函数中添加l2 -> next = NULL; 的解决方案。
但我想知道为什么输出会有所不同。编译器中是否存在错误,或者我没有初始化指向 NULL 的指针是错误的,即使它在大多数编译器中都有效?
【问题讨论】:
-
因为没有分配
NULL,您正在调用未定义的行为。 -
使用未初始化的变量是未定义的行为。
-
关于:
return l2; }; int main(){右大括号后的杂散分号;在现代编译器上无法编译 -
@user3629249:我已经在 GCC、Clang 和 TCC 上进行了尝试,并且在所有这些上都可以正常编译。
-
编译时,始终启用所有警告。 (对于
gcc,至少使用:-Wall -Wextra -pedantic -Werror -std=gnu11)然后修复警告