1

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

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

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

4

2 回答 2

7

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

存储结果realloc()

char* t = realloc(string, filelen);
if (t)
{
    string = t;
}
于 2013-04-24T16:32:56.387 回答
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" );
}
于 2013-04-24T16:34:08.280 回答