1

我在 Jon Erickson 的书Hacking: The Art of Exploitation中找到了这个来源,

userid = getuid(); // get the real user ID
// Writing data
if(write(fd, &userid, 4) == -1)  // write user ID before note data
    fatal("in main() while writing userid to file");
write(fd, "\n", 1); // terminate line

我尝试编译这段代码,发现在我写的文件上,userid(就是我上面代码中写的)不对;他们只是写了奇怪的字符(我认为在这里写它并不重要)。所以问题是我试图将一个传递int给一个需要的函数char *,因为我想写的文件上的结果是错误的。

所以这是一个错误,对吧?

4

2 回答 2

5

write()函数需要一个void *作为它的缓冲区;它写入任意二进制数据。如果您需要转换为字符串,请使用printf().

您没有显示 的​​声明userid,但该write()行应写为:

if (write(fd, &userid, sizeof(userid)) != sizeof(userid))

这将检测短写入(不太可能是整数类型的问题)和其他问题,并且无论userid. 因此,该行的原始版本可以说是有问题的。否则,错误似乎在您的期望中,而不是代码本身。

于 2013-02-09T16:01:26.220 回答
2

不,这不是错误,而是您的误解。该write调用将只写入内存中的内容,即二进制表示。你需要一些东西fprintf来获得一个可读的版本。

例如,7 的二进制表示可能是四个字节 0、0、0 和 7,这不太可能看起来像文本表示,单个字节 55(假设为 ASCII)。

It's also a bad idea to hardcode type lengths like 4 for an integer since that's not portable. Better would be to use something like sizeof(userid).

于 2013-02-09T16:02:55.283 回答