本文来自“The most stupid C bug ever”,很有意思,分享给大家。我相信这样的bug,就算你是高手你也会犯的。你来看看作者犯的这个Bug吧。。
首先,作者想用一段程序来创建一个文件,如果有文件名的话,就创建真正的文件,如果没有的话,就调用?tmpfile()?创建临时文件。他这段程序就是HTTP下载的C程序。code==200就是HTTP的返回码。
else if (code == 200) { // Downloading whole file /* Write new file (plus allow reading once we finish) */ // FIXME Win32 native version fails here because // Microsoft\\\'s version of tmpfile() creates the file in C:\\\\ g = fname ? fopen(fname, \"w+\") : tmpfile(); }
然后,作者觉得需要写一个跨平台的编译:
#ifdef _WIN32 #define tmpfile w32_tmpfile #endif FILE * w32_tmpfile ( void ) { //code for Windows; }
搞定!编译程序,运行。靠!居然没有调用到我的w32_tmpfile(),什么问题?调试,单步跟踪,果然没有调用到!难道是问号表达式有问题?改成if - else 语句,好了!
#ifdef _WIN32 # define tmpfile w32_tmpfile #endif FILE * w32_tmpfile ( void ) { code for Windows; } else if (code == 200) { // Downloading whole file /* Write new file (plus allow reading once we finish) */ // FIXME Win32 native version fails here because // Microsoft\\\'s version of tmpfile() creates the file in C:\\\\ //g = fname ? fopen(fname, \"w+\") : tmpfile(); if(NULL != fname) { g = fopen(fname, \"w+\"); } else { g = tmpfile(); } }
不能正常工作的代码
/* Write new file (plus allow reading once we finish) */ // FIXME Win32 native version fails here because // Microsoft\\\'s version of tmpfile() creates the file in C:\\\\
你看到了最后那个C:\\\\吗?在C中,“\\\\” 代表此行没有结束,于是,后面的代码也成了注释。这就是这个bug的真正原因!
而之所以改成if-else能工作的原因是因为作者注释了老的问号表达式的代码,所以,那段能工作的代码成了:
float result = num/*pInt; .... /* some comments */ num++;
Holly Shit! 我的代码成了:
<pre class="\"brush:" cpp;="" title:="" ;="" notranslate\"="" style="font-size: 16px; line-height: 25px;">float result = num/num++;妈的!我的这个错误在愚蠢程度上和上面那个作者出的错误有一拼。
(全文完)