2016-07-24 12 views
-2

load関数ポインタfileが指すファイルの内容をロードしlengthcontentと長さでその位置を保存しようとします。コードは正常に動作しますが、Valgrindはreallocを使用している間に "無効書き込みwith fread"といくつかのメモリリークを表示します。Valgrindの「無効関数freadでサイズ4の書き込み」とメモリリークを示す

以下はコードです:

bool load(FILE* file, BYTE** content, size_t* length) { 
    // providing default values to content and length 
    *content = NULL; 
    *length = 0; 

    // initializing buffer to hold file data 
    int size = 512; 
    BYTE* buffer = NULL; 
    buffer = malloc(size); 
    if(buffer == NULL) 
     return false; 

    // bytes_read will store bytes read at a time  
    int bytes_read = 0; 

    // reading 512 bytes at a time and incrmenting writing location by 512 
    // reading stops if less than 512 bytes read 
    while((bytes_read = fread(buffer + size - 512 , 1, 512, file)) == 512) 
    { 
     //increasing the size of 
     size = size + 512; 
     if(realloc(buffer,size) == NULL) 
     { 
      free(buffer); 
      return false; 
     } 
    } 

    // undoing final increment of 512 and increasing the size by bytes_read on last iteration 
    size = size - 512 + bytes_read; 

    // triming buffer to minimum size 
    if(size > 0) 
    { 
     BYTE* minimal_buffer = malloc(size + 1); 
     memcpy(minimal_buffer, buffer, size); 
     minimal_buffer[size] = '\0'; 
     free(buffer);  
     *content = minimal_buffer; 
     *length = size; 
     return true; 
    } 

    return false; 
} 

答えて

3

あなたの問題はここにある:

if(realloc(buffer,size) == NULL) 

これは、バッファを再割り当てしますが、新しいポインタを保存しないでください。 realloc関数は、新しいメモリ領域を割り当ててそこにデータをコピーすることができます。新しいポインタを返します。

重要なお知らせ:realloc関数に渡すポインタに再度割り当てないでください。一時変数を使用してください。その後reallocが失敗した場合、元のポインタを失うことはなく、正常にクリーンアップできます。

関連する問題