为什么malloc在这里引起内存损坏?

Art*_*ner -3 c malloc rpc memory-management memory-corruption

我不断收到以下错误:

*** Error in `./vice': malloc(): memory corruption: 0x08e77530 ***
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

相关代码为:

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;
}
Run Code Online (Sandbox Code Playgroud)

让我解释一下代码的作用。这是一个名为“ 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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

我一直在阅读有关这种类型的错误的信息,但我不了解这种特殊情况的问题。

ams*_*ams 5

malloc不“挑衅”腐败;malloc 检测到它。

这个错误告诉您, malloc这次调用之前,某些内容已经在堆元数据上进行了乱写。您可能有缓冲区溢出。

malloc此代码中的两个调用都在任何内容写入内存之前,因此溢出很可能发生在其他地方。(我没有详细检查代码是否正确,但实际上是在这里。)


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