2016-08-07 20 views
2

このコードは(ヌル終端文字列&を含むファイルが欲しかった文字列のインデックスを提供する必要があります)ファイルからヌル終端文字列を読み込みます。

ダブル無料または破損(fasttop)

エラー:

*** Error in `./main': double free or corruption (fasttop): 0x090a4a80 *** 
Aborted 

はコード:

char *tmp_realloc=NULL; 
char *sstring=NULL; 
int i=1; 

/*Set file pointer to point string*/ 
fseek(fh,index,SEEK_SET); 

sstring=(char*)malloc(sizeof(char)); 
    if(sstring == NULL) 
     return NULL; 

tmp_realloc=sstring; 

while((*(sstring+i-1)=(char)fgetc((FILE*)fh)) != 0x0) { 
    /*reallocate more memory*/ 
    tmp_realloc=(char*)realloc((char*)sstring,++i); 

    /*if not same address copy old to new & set old to point new*/ 
     if(tmp_realloc != sstring){ 
      strcpy((char*)tmp_realloc,(char*)sstring); 
      free(sstring); 
      sstring=tmp_realloc; 
     } 
} 

あなたがこの問題を引き起こしているものをポインタ(どのような理由のために&)を教えてください。

答えて

4

一部を削除

/*if not same address copy old to new & set old to point new*/ 
if(tmp_realloc != sstring){ 
    strcpy((char*)tmp_realloc,(char*)sstring); 
    free(sstring); 
    sstring=tmp_realloc; 
} 

これは、それが成功した場合realloc()があなたのために行いますまさに(memcpy()のようなものではなくstrcpy()のに使用されます)ほとんどです。その代わりにエラーチェックを挿入し、エラーが見つからなければtmp_reallocsstringに割り当てるだけです。

またchar*からchar*が完全に役に立たないようだキャスト、なぜこれらのキャストを削除しませんか?

+0

それは今働いて、ありがとうございました。だから私は、エラーは私が 'realloc'によってすでに行われている' free(sstring) 'を行ったことから来ていると理解していますので、メモリ解放は同じポインタに対して2回行われましたか? –

関連する問題