#include <stdio.h>
#include <string.h>
int main()
{
char arrDst[5] = {0};
char arrSrc[10] = "123456";
memcpy( arrDst, arrSrc, sizeof( arrSrc ) );
return 0;
}
Here in this program it is clear that there is a memory corruption.
Is there any option in gcc compiler by which I can recognize this problem at compile time?
Note: I used valgrind --leak-check=full
, but it doesn't help.
GCC 4.3+ now has -Q --help=warnings , and you can even specify --help=warnings,C to just print out the C related warnings.
You can use the -Werror compiler flag to turn all or some warnings into errors. Show activity on this post. You can use -fdiagnostics-show-option to see the -W option that applies to a particular warning. Unfortunately, in this case there isn't any specific option that covers that warning.
The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)
$ gcc -Wall -O1 t.c
In file included from /usr/include/string.h:642:0,
from t.c:3:
In function ‘memcpy’,
inlined from ‘main’ at t.c:13:9:
/usr/include/bits/string3.h:52:3: warning: call to __builtin___memcpy_chk
will always overflow destination buffer [enabled by default]
GCC can recognize some of these. That generally requires turning on optimizations (at least -01
) and warnings (-Wall
, add -Wextra
too).
It may not scale to the large program you are really interested in, but you can find this error with Frama-C:
$ frama-c -cpp-command "gcc -C -E -I`frama-c -print-share-path`/libc/ -nostdinc" mem.c `frama-c -print-share-path`/libc/fc_runtime.c -val
...
[value] computing for function memcpy <- main.
Called from mem.c:13.
.../libc/string.h:54:[value] Function memcpy: precondition got status invalid.
This message means that you are calling memcpy()
with arguments that do not satisfy its contract. In this case the pre-condition that fails is the first in the list, about the validity of the destination for writing:
/*@ requires \valid(((char*)dest)+(0..n - 1));
@ requires \valid_read(((char*)src)+(0..n - 1));
@ requires \separated(((char *)dest)+(0..n-1),((char *)src)+(0..n-1));
@ assigns ((char*)dest)[0..n - 1] \from ((char*)src)[0..n-1];
@ assigns \result \from dest;
@ ensures memcmp((char*)dest,(char*)src,n) == 0;
@ ensures \result == dest;
@*/
extern void *memcpy(void *restrict dest,
const void *restrict src, size_t n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With