Search code examples
cpointersvalgrindscanf

Valgrind Invalid read of size 1 (sscanf)


Somehow Valgrind shows an error at the first lines of my program:

int main(int argc, char** argv) {
  int i, r;
  sscanf(argv[1], "%d", &r);

  return 0;
}

Valgrind reports:

==18674== Invalid read of size 1
==18674==    at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so)
==18674==    by 0x400DE3: main (test_b_arbre.c:18)
==18674==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==18674== 
==18674== 
==18674== Process terminating with default action of signal 11 (SIGSEGV)
==18674==  Access not within mapped region at address 0x0
==18674==    at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so)
==18674==    by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so)
==18674==    by 0x400DE3: main (test_b_arbre.c:18)

I went through some similar questions, but I didn't find how to fix it... How I run the program:

valgrind --leak-check=yes --track-origins=yes ./b_arbre 1 2 3 4 5 6

Solution

  • I compiled your exact program on a 64 bit x86_64 Linux (seeing hints of 64 bit libraries in your Valgrind output). The issue doesn't reproduce. I get a warning about the sscanf implicit declaration not being correct, but that is a red herring.

    I also tried on 64 bit Power PC Linux. Clean Valgrind also.

    (Of course, the null pointer dereference occurs if the program is called with no arguments, in which case argv[argc] is done; but the issue is described as occurring with arguments.)

    The problem is likely that the executable being tested doesn't match the source code.