改进我的 C 编码并发现代码问题
Improve my C coding and find issues with code
我是 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] = '[=10=]'; // 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] = '[=10=]'; // null terminate buf
return 0;
}
您应该检查 read() 中的 return 值,以确保您没有收到错误或 EOF。
我是 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] = '[=10=]'; // 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] = '[=10=]'; // null terminate buf
return 0;
}
您应该检查 read() 中的 return 值,以确保您没有收到错误或 EOF。