我是 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;
}
最佳答案
我已将问题放在代码的注释中。
int main(){
char *buffer;
int lent=0;
//int i
read(fd, &lent, sizeof(lent)); // You never declare or set fd -- you need int fd = open("filename", O_RDONLY);
if ((lent+1) < 0) { // This will allow lent == -1, even though that's negative
error ("negative length"); // error() is not defined
return 0;
}
buffer = malloc(lent+1);
if (buffer==NULL) {
exit(EXIT_FAILURE);
}
read(fd,buffer,lent); // depending on what fd refers to, read() might return less than lent bytes, it returns how many bytes it read
buffer[lent] = '\0'; // null terminate buf
return 0;
}
您应该检查 read() 的返回值,以确保没有收到错误或 EOF。
关于c - 改进我的 C 编码并查找代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59006323/