realloc()问题,没有分配

Nat*_*Kup 1 c c++ unix linux

我正在尝试读一个字符串

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
Run Code Online (Sandbox Code Playgroud)

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

   malloc: *** error for object 0x1001000e0: pointer being realloc'd was not allocated
Run Code Online (Sandbox Code Playgroud)

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

hmj*_*mjd 7

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

存储结果realloc():

char* t = realloc(string, filelen);
if (t)
{
    string = t;
}
Run Code Online (Sandbox Code Playgroud)