【发布时间】:2012-08-24 14:54:16
【问题描述】:
当我玩弄一些在线网站提供的代码时,我遇到了一个我从未预料到的奇怪故障:一个变量突然改变了它的值而没有任何手动赋值。
下面是代码:
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
printf("rc is equal to %d\n", rc); // should print out 1
if (rc != 1) die("Failed to write Database.");
rc = fflush(conn->file);
printf("rc is equal to %d\n", rc); // should print out 0
if (rc == -1); die("Cannot flush database"); // error handling
// error comes up because rc suddenly changes to -1
我不明白它是怎么发生的,但想知道为什么一个变量在 C 中不应该发生变化时突然发生变化。
代码来源: http://c.learncodethehardway.org/book/learn-c-the-hard-waych18.html (Database_write下的堆栈和内存)
顺便说一句,我在 Mac osx 10.6 雪豹的终端中使用 vim。
【问题讨论】:
-
注意:如果您使用
-Wall -Wextra编译,GCC 会准确地告诉您错误在哪里。 Clang 会默认告诉你。 -
低悬的水果抽奖......也许我们可以得到另外十几个提到额外分号的答案。
标签: c variable-assignment