2016-07-24 74 views
-2

load函数试图加载由指针指向file文件的内容,并在content和长度保存在length其位置。代码工作正常,但Valgrind在使用realloc时显示“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失败,你不会失去原始指针,并可以优雅地清理。