【发布时间】:2019-11-23 09:39:42
【问题描述】:
我是 C 编码的新手,我正在尝试找出我的代码可能遇到的问题,以帮助我构建更安全的 C 代码编写。谁能告诉我这段代码的问题是什么?我知道malloc 这里可能会因为内存泄漏而失败。但是代码还有其他问题吗?初始化fd 的最佳方式是什么?如果这个问题不够有力,请见谅。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
char *buffer;
int lent = 0;
//int i
read(fd, &lent, sizeof(lent));
if ((lent + 1) < 0) {
error("negative length");
return 0;
}
buffer = malloc(lent + 1);
if (buffer == NULL) {
exit(EXIT_FAILURE);
}
read(fd, buffer, lent);
buffer[lent] = '\0'; // null terminate buf
return 0;
}
【问题讨论】:
-
你从来没有设置过
fd。 -
是的,我知道 fd 没有设置。我问什么是设置 fd 的最佳方法。 @kaylum 我只是想弄清楚这里可能会发生什么错误。我正在编写另一个代码,但我需要知道他们是否在这方面出现问题,我应该避免这种事情
-
你通过调用
open()来初始化它,还能有什么选择? -
仅供参考,如果您希望审核您的代码,Code Review 是一个更合适的网站。 Stackoverflow 是针对特定编码问题的。