2013-04-24 61 views
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 
    realloc(string, filelen); //realloc with new length 

有時這種崩潰並出現以下錯誤:

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

,但有時不,我不知道如何要解決這個問題。

+3

是你們沒有閱讀文檔... – 2013-04-24 16:33:57

回答

7

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

商店realloc()結果:當你打電話realloc()

char* t = realloc(string, filelen); 
if (t) 
{ 
    string = t; 
} 
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 
    char* tempPtr = realloc(string, filelen); //realloc with new length 

    if(tempPtr) string = tempPtr; 
    else printf("out of memory"); 
}