c - 改进我的 C 编码并查找代码问题

标签 c file malloc valgrind

我是 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/

相关文章:

c - Valgrind 1017 calloc/memcopy of struct dirent OK,第 1018 次 -- 无效读取

自定义 Eclipse 代码辅助

c - 为什么 unsigned int 而不是 strlcat 和 strlcpy 的 void?

php - 在 Windows 上使用 Ping 将换行符回显到文件

c - 使用字符串和 Malloc/Realoc

linux - 为什么malloc依赖mmap从某个阈值开始?

c - 如果我只想接收 C/TCP 中的数据,是否需要 connect()?

c - 释放共享内存

c - c中文件打开模式的区别

ios - objective c iOS 文件结构困惑