如何修复我的代码中的以下 malloc 错误?

问题描述 投票:0回答:2

我正在尝试编写一个程序,在 Linux 上使用 FIFO 连接客户端和服务器,然后当客户端向服务器发送消息时,服务器将该消息打印到控制台。现在我将程序设计如下:当客户键入“嘿,你好吗?”之类的内容时。构建了一条带有一些额外信息的消息。该消息具有以下格式:“[客户端的 PID/消息的大小:消息]”。因此,如果客户端的 PID 为 4172,那么在我们的示例中,组合消息为:“[4172/17:Hey, how are you?]”。此消息被发送到服务器,服务器对其进行分解,只打印没有额外信息(如客户端的 PID 等)的消息。现在我包含这些信息是为了不浪费内存,因为这使我能够使用动态内存分配.该程序第一次运行。客户端和服务器连接,当客户端发送消息时,服务器打印它就好了。但是,当我尝试再次向它发送消息时,出现以下错误:

server.out: malloc.c:2617: sysmalloc: Assertion (old_top == initial_t…
…op (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. Aborted(core dumped).

服务器代码的相关位是:

//delimCheckBuffer is an array of size 1

void readUntilColon(int fd, char* buffer, size_t index) {
    while(read(fd, delimCheckBuffer, 1) > 0) {
        if(delimCheckBuffer[0] == ':') {
            buffer[index] = ':';
            break;
        }
        buffer[index] = delimCheckBuffer[0];
        ++index;
    }
}

char* messageReconstruct(int fdOfFIFO) {
    char* message = calloc(15, sizeof(char)); //Took into account the 4 symbols : / [ ] and 
    long NumOfCharsInMessage;                 //assumed that PID and length of message are at most
    size_t index = 0;                         //7 and 4 digits respectively.

    readUntilColon(fdOfFIFO, message, 1);
    NumOfCharsInMessage = findNumOfCharsInMessage(message);
    
    free(message);

    message = calloc(NumOfCharsInMessage, sizeof(char));

    while(read(fdOfFIFO, delimCheckBuffer, 1) > 0) {
        if(delimCheckBuffer[0] == ']')
            break;
        message[index] = delimCheckBuffer[0];
        ++index;
    }

    return message;
}

我试着用 Valgrind 调试它。它表示在 readUntilColon() 中大小 1 的无效写入。它特别指出

buffer[index] = delimCheckBuffer[0];
是问题所在。但是我仍然不明白这一点有什么问题。如果有人能向我解释,那就太好了。谢谢。

c linux systems-programming
2个回答
1
投票

你需要检查你是否没有覆盖缓冲区

void readUntilColon(int fd, char* buffer, size_t index, size_t size) {
    while(read(fd, delimCheckBuffer, 1) > 0) {
        if(index < size)
        {
            if(delimCheckBuffer[0] == ':') {
                buffer[index] = ':';
                break;
            }
            buffer[index] = delimCheckBuffer[0];
            ++index;
        }
    }
}

相应地调用它。添加更多检查


0
投票

您的索引未被检查,因此超过您的缓冲区并非不可能,

可能只是你的 fd 格式不正确

        buffer[index] = delimCheckBuffer[0];
© www.soinside.com 2019 - 2024. All rights reserved.