我正在用 valgrind 检查一些代码,我得到了这个错误:
==7001== Invalid read of size 1
==7001== at 0x402E21B: strstr (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==7001== by 0x8049742: replace_in_file (functions.c:191)
==7001== by 0x8049C55: parse_dir (functions.c:295)
==7001== by 0x8049059: main (main.c:214)
==7001== Address 0x42018c3 is 0 bytes after a block of size 3 alloc'd
==7001== at 0x402B018: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==7001== by 0x80496EC: replace_in_file (functions.c:183)
==7001== by 0x8049C55: parse_dir (functions.c:295)
==7001== by 0x8049059: main (main.c:214)
代码片段如下所示:
long int replace_in_file(char **sets, FILE *file, char *path, const char *mode){
long int n = 0, size = 0, len, remaining_len;
char *buffer,
*found,
*before,
*after;
size = file_size(file);
if(-1 != size){
buffer = malloc(size * sizeof(char));
rewind(file);
fread(buffer, 1, size, file);
int i=0;
do{
do{
found = strstr(buffer, sets[i]); // LINE 191
if(NULL != found && '\0' != sets[i][0]){
//rest of code...
我无法理解为什么会出现该错误,因为一切都按预期工作,并且在调试器中每个变量似乎都很好。
出了什么问题,我该如何解决?