red888
red888

Reputation: 31620

why doesn't valgrind detect excess elements in arrays

I am learning C and going through a tutorial that includes the use of valgrind. I am still learning about what valgrind is actually doing and was wondering if someone could explain why it does not detect any errors in the following code:

#include <stdio.h>

int main(int argc, char *argv[])    
{
    int numbers[4] = {0,1,2,3,4};

    // first, print them out raw
    printf("numbers: %d %d %d %d %d\n",
           numbers[0], numbers[1],
           numbers[2], numbers[3],
           numbers[4]);

    return 0;
}

I do get compiler errors:

greggery@Lubu:~/code$ make lc
cc -Wall -g    lc.c   -o lc
lc.c: In function ‘main’:
lc.c:5:2: warning: excess elements in array initializer [enabled by default]
lc.c:5:2: warning: (near initialization for ‘numbers’) [enabled by default]

But when I run it against valgrind it doesn't see anything wrong:

==2300== Memcheck, a memory error detector
==2300== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2300== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2300== Command: ./lc
==2300== 
numbers: 0 1 2 3 69156864
==2300== 
==2300== HEAP SUMMARY:
==2300==     in use at exit: 0 bytes in 0 blocks
==2300==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==2300== 
==2300== All heap blocks were freed -- no leaks are possible
==2300== 
==2300== For counts of detected and suppressed errors, rerun with: -v
==2300== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Isn't there a memory issue here because I am adding an extra element to the array? I thought valgrind would find a problem with the last element because it is outside the array.

Upvotes: 0

Views: 894

Answers (2)

nio
nio

Reputation: 5289

Taken from valgrind docs. It's an answer to a question named Why doesn't Memcheck find the array overruns in this program?

Unfortunately, Memcheck doesn't do bounds checking on global or stack arrays. We'd like to, but it's just not possible to do in a reasonable way that fits with how Memcheck works. Sorry.

However, the experimental tool SGcheck can detect errors like this. Run Valgrind with the --tool=exp-sgcheck option to try it, but be aware that it is not as robust as Memcheck.

Upvotes: 4

pradipta
pradipta

Reputation: 1744

Your array is stored in stack area and Valgrind checks for the leak in heap area.It check for leak of memory allocated by dynamic allocation so you are not getting any detection by Valgrind.

If you really want to see the effect then use bellow code

int main()
{
  int *p=malloc(6);
}

and use Valgrind to check the memory leak.

Upvotes: 6

Related Questions