Does the gcc compiler have the ability to recognize memory corruption at compile time?

#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 memory corruption.

Is there any option in the gcc compiler with which I can recognize this problem at compile time?

Note: I used valgrind --leak-check=full , but this does not help.

+6
source share
2 answers
 $ gcc -Wall -O1 tc In file included from /usr/include/string.h:642:0, from tc:3: In function 'memcpy', inlined from 'main' at tc:13:9: /usr/include/bits/string3.h:52:3: warning: call to __builtin___memcpy_chk will always overflow destination buffer [enabled by default] 

GCC may recognize some of them. Usually you need to enable optimization (at least -01 ) and warnings ( -Wall , add -Wextra too).

+7
source

It may not scale for a large program of interest to you, but you may 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 precondition that fails is the first in the list about the validity of the destination for the record:

 /*@ 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); 
+2
source

Source: https://habr.com/ru/post/944193/


All Articles