【问题标题】:Improve my C coding and find issues with code改进我的 C 编码并发现代码问题
【发布时间】: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 是针对特定编码问题的。

标签: c file malloc valgrind


【解决方案1】:

我已将问题放在代码中的 cmets 中。

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。

【讨论】:

  • 我在评论中添加了声明
猜你喜欢
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2015-02-17
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多