realloc()问题,没有分配

时间:2013-04-24 16:31:13

标签: c++ c linux unix

我正在尝试读取字符串

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

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

2 个答案:

答案 0 :(得分:7)

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

存储realloc()的结果:

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

答案 1 :(得分:1)

拨打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" );
}