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

时间:2014-10-07 10:24:55

标签: c memory-management malloc rpc memory-corruption

我一直收到以下错误:

*** 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-&gt; fname中给出的名称的文件。如果open成功,open_file_1_svc将尝试在result.characters中复制文件的内容,以这种方式将文件内容的副本发送到客户端。 number_characters将允许我知道它们之间是否有空字节。

当我尝试为我即将阅读的文件部分分配一些内存时,会出现错误。

我一直在读这种类型的错误,但我不明白这个特殊情况有什么问题。

1 个答案:

答案 0 :(得分:4)

malloc不会“挑起”腐败; malloc 检测到

此错误告诉您在调用 malloc之前已经在堆元数据上乱写了一些内容(此时);你可能有一个缓冲区溢出。

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


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