使用valgrind在strstr()中读取大小1无效

Pau*_*aul 2 c valgrind strstr

我正在用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)
Run Code Online (Sandbox Code Playgroud)

代码段如下所示:

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...
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么我会得到这个错误,因为一切都按预期工作,并且在调试器中每个变量似乎都很好.

有什么问题,我该如何解决?

Fat*_*ror 5

fread()没有 NUL,终止它读取数据,但strstr()需要一个空终止字符串.您应该分配大小+ 1个字节并明确添加nul-terminator以确保安全.