20110827

标 题: C语言中史上最愚蠢的Bug(zz) 转载

发信人: josephpei (Nikon,感动常在), 信区: CProgramming
标 题: C语言中史上最愚蠢的Bug(zz)
发信站: 水木社区 (Fri Aug 26 15:59:46 2011), 站内

http://coolshell.cn/articles/5388.html

本文来自"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) */
g = fname ? fopen(fname, "w+") : tmpfile();
}

但是这个程序,只能在Unix/Linux下工作,因为 Microsoft 的?tmpfile()的实现?居然选择了 C:\
作为临时文件的存放目录,这对于那些没有管理员权限的人来说就出大问题了,在Windows
7下,就算你有管理员权限也会有问题。所以,上面的程序在Windows平台下需要用不同的方式来处理,不能直接使用Windows的tmpfile()函数。

于是作者就先把这个问题记下来,在注释中写下了FIXME:

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();
}

然后,作者觉得需要写一个跨平台的编译:

FILE * tmpfile ( void ) {
#ifndef _WIN32
return tmpfile();
#else
//code for Windows;

No comments: