realloc(): 无效的下一个大小(核心转储) [英] realloc(): invalid next size (core dumped)

查看:67
本文介绍了realloc(): 无效的下一个大小(核心转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的函数,每次我想添加一个字符时都会重新分配缓冲区,它一直工作到我想第 24 次重新分配.然后 realloc(): invalid next size 出现.代码如下:

I have a simple function that reallocs buffer every time I want to add one char, It works till I want to realloc 24th time. Then realloc(): invalid next size appears. Here is the code:

char * addDataChunk(char * data,char c)
{
    char * p;
    if(data==NULL)
    {
        data=(char*)malloc(sizeof(char)*2);
        data[0]=c;
        data[1]='\0';
        return data;
    }
    else
    {
        if(p = (char*)realloc(data,((strlen(data)+1)*sizeof(char))))
        {
            data = p;
        }
        else
        {
            printf("realloc error\n");
        }
        data[strlen(data)] = c;
        data[strlen(data)+1] = '\0';
        return data;
    }
}

和错误:

*** Error in `./bootstrap': realloc(): invalid next size:     0x0000000000b9f2a0 ***
Aborted (core dumped)

推荐答案

主要错误很可能在这里:

The main error is most likely here:

data[strlen(data)] = c;
data[strlen(data)+1] = '\0';

您首先用字符覆盖空终止符.然后您尝试获取不再有空终止符的字符串的长度,这意味着您将运行分配的内存,这意味着未定义的行为.您的分配将导致任何大小.然后你继续.

You first overwrite the null terminator with the character. Then you try to get the length of the string which doesn't have the null terminator anymore, which means you will run over the memory allocated, which means undefined behaviour. Your allocation will result in whatever size. And then you continue.

之前没有发生的原因很可能是因为分配的内存在某些时候碰巧有一个空值,并且它保持在合理的范围内.但不是永远.

The reason why it doesn't happen before is most likely because the memory allocated happens to have a null at some point and it stays within reasonable boundaries. But not forever.

最好的方法是跟踪大小,而不是每次都使用昂贵的 strlen(),但如果您确实必须/想要,请先将值存储在变量中.

The best way would be to keep track of the size and not use the expensive strlen() every time, but if you really must/want to, store the value in a variable first.

size_t pos = strlen(data);
data[pos] = c;
data[pos+1] = '\0';

甚至切换它们:

data[strlen(data)+1] = '\0';
data[strlen(data)] = c;

此外,您将重新分配完全相同的内存量,因为 strlen()+1 是从头开始分配的 2 个字节(字符串 + 空终止符).应该是strlen()+2.

Also you would reallocate the exact same amount of memory since strlen()+1 is the allocated 2 bytes from the beginning (string + null terminator). It should be strlen()+2.

同样作为样式问题,sizeof(char) 根据定义为 1,因此除非您觉得它增加了一些清晰度,否则您不需要使用它.

Also as a style issue, sizeof(char) is by definition 1 so you don't need to use it unless you feel it adds something to clarity.

这篇关于realloc(): 无效的下一个大小(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆