gpt4 book ai didi

c - 为什么 malloc 会在这里引发内存损坏?

转载 作者:行者123 更新时间:2023-11-30 20:47:19 25 4
gpt4 key购买 nike

我不断收到以下错误:

*** Error in `./vice': malloc(): memory corruption: 0x08e77530 ***
Aborted (core dumped)

相关代码为:

open_result *
open_file_1_svc(open_args *argp, struct svc_req *rqstp)
{
static open_result result;
int obtained_fd;
int just_read;
int total_read = 0;
int max_bytes_read = 1024;
char *ptr_file;
char *pathName = "MyFiles/"; // strlen = 8
int toReserve;

xdr_free((xdrproc_t)xdr_open_result, (char *)&result);

// Construct full name of the file (in "MyFiles")
toReserve = strlen(argp->fname) + strlen(pathName) + 1; // "\0"
char *fullName = malloc(toReserve*sizeof(char));
fullName = strdup(pathName);
fullName = strcat(fullName, argp->fname);

// Call to open in POSIX
obtained_fd = open(fullName, argp->flags);

result.fd = obtained_fd;

/* If there was an error while reading, the error code will be sent, but not
the file (it might not even exist) */
if (obtained_fd < 0) {
result.characters = "";
result.number_characters = 0;
}
/* If the file opening was successful,
both the fd and the file will be sent */
else {
char *file_just_read = malloc(max_bytes_read * sizeof(char)); // This is the problem
ptr_file = file_just_read;

/* Reading the file byte by byte */
while((just_read = read(obtained_fd, ptr_file, max_bytes_read)) > 0) {
total_read += just_read;
file_just_read = realloc(file_just_read, (total_read+max_bytes_read) * sizeof(char));
ptr_file = file_just_read + total_read;
}
result.characters = file_just_read;
result.number_characters = total_read;
}
return &result;
}

让我解释一下这段代码的作用。这是一个名为“vice”的服务器,它通过 RPC 与其客户端进行通信。该函数应该接收“open_args”并返回“open_result”。这些在“vice.x”文件中定义。该文件的相关部分是:

struct open_args {
string fname<>;
int flags;
};

struct open_result {
string characters<>;
int number_characters;
int fd;
};

open_file_1_svc 应该尝试打开 MyFiles 目录中 argp->fname 中指定名称的文件。如果打开成功,open_file_1_svc 将尝试复制 result.characters 中的文件内容,以这种方式将文件内容的副本发送到客户端。 number_characters 可以让我知道中间是否有空字节。

当我尝试为我要读取的文件部分分配一些内存时,出现错误。

我一直在阅读有关此类错误的信息,但我不明白这种特殊情况出了什么问题。

最佳答案

malloc 不会“引发”损坏; malloc 检测它。

此错误告诉您,在调用 malloc 之前(这次),堆元数据上已被涂写了一些内容;您可能存在缓冲区溢出。

此代码中的两个 malloc 调用都是在写入内存之前进行的,因此溢出很可能发生在其他地方。 (我没有详细检查这个代码是否正确,但这是事后的结果。)

<小时/>

编辑:我错过了 strdup 内的隐式 malloc 调用。这将导致溢出,因为重复的字符串具有较小的分配。我认为你的意思是 strcpy,而不是 strdup

关于c - 为什么 malloc 会在这里引发内存损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26233862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com