【问题标题】:realloc() issue,was not allocatedrealloc() 问题,未分配
【发布时间】:2013-04-24 16:31:13
【问题描述】:

我正在尝试读取一个字符串

char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
    filelen=filelen+readch; //string length
    for (d=0;d<readch;d++)
        *start_string++=buffer[d]; //append buffer to str
    realloc(string, filelen); //realloc with new length

有时这会崩溃并出现以下错误:

   malloc: *** error for object 0x1001000e0: pointer being realloc'd was not allocated

但有时不是,我不知道如何解决它。

【问题讨论】:

  • Y U 人没有阅读文档...

标签: c++ c linux unix


【解决方案1】:

realloc() 不会更新传递给它的指针。如果realloc()成功,则传入的指针为free()d,并返回分配的内存地址。在发布的代码中realloc() 将尝试多次free(string),这是未定义的行为。

存储realloc()的结果:

char* t = realloc(string, filelen);
if (t)
{
    string = t;
}

【讨论】:

    【解决方案2】:

    当您调用realloc() 时,字符串的地址可能会发生变化。

    char *string=malloc(sizeof(char));
    char *start_string=string; //pointer to string start
    while ((readch=read(file, buffer, 4000))!=0){ // read
        filelen=filelen+readch; //string length
        for (d=0;d<readch;d++)
            *start_string++=buffer[d]; //append buffer to str
        char* tempPtr = realloc(string, filelen); //realloc with new length
    
        if( tempPtr ) string = tempPtr;
        else printf( "out of memory" );
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 1970-01-01
      • 2016-01-08
      • 2018-03-20
      • 2010-11-07
      • 2021-03-16
      • 2018-07-06
      • 2020-08-26
      • 1970-01-01
      相关资源
      最近更新 更多