Valgrind 显示 "invalid write of size 4 at fread" 和内存泄漏
Valgrind showing "invalid write of size 4 at fread" and memory leaks
下面的 load
函数尝试加载指针 file
指向的文件的内容,并将其位置保存在 content
中,长度保存在 length
中。代码工作正常,但 Valgrind 在使用 realloc
.
时显示 "invalid write at fread" 错误和几个内存泄漏
代码如下:
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] = '[=11=]';
free(buffer);
*content = minimal_buffer;
*length = size;
return true;
}
return false;
}
您的问题在这里:
if(realloc(buffer,size) == NULL)
它重新分配缓冲区,但您不保存新指针。 realloc
函数可以分配一个新的内存区域并将数据复制到那里。它 returns 新指针。
重要说明:不要重新分配回传递给 realloc
函数的指针,使用临时变量。然后,如果 realloc
失败,您不会丢失原始指针并且可以优雅地清理。
下面的 load
函数尝试加载指针 file
指向的文件的内容,并将其位置保存在 content
中,长度保存在 length
中。代码工作正常,但 Valgrind 在使用 realloc
.
代码如下:
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] = '[=11=]';
free(buffer);
*content = minimal_buffer;
*length = size;
return true;
}
return false;
}
您的问题在这里:
if(realloc(buffer,size) == NULL)
它重新分配缓冲区,但您不保存新指针。 realloc
函数可以分配一个新的内存区域并将数据复制到那里。它 returns 新指针。
重要说明:不要重新分配回传递给 realloc
函数的指针,使用临时变量。然后,如果 realloc
失败,您不会丢失原始指针并且可以优雅地清理。