簡體   English   中英

realloc()問題,未分配

[英]realloc() issue,was not allocated

我正在嘗試讀取字符串

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

但有時沒有,我不知道如何解決。

realloc()不會更新傳遞給它的指針。 如果realloc()成功,則傳入的指針為free() d,並返回分配的內存的地址。 在發布的代碼中, realloc()將嘗試多次free(string) ,這是未定義的行為。

存儲realloc()的結果:

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

調用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" );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM