gcc编译器是否有任何选项可以在编译时识别内存损坏?

Sub*_*jit 6 c gcc

#include <stdio.h>
#include <string.h>

int main()
{
  char arrDst[5] = {0};
  char arrSrc[10] = "123456";
  memcpy( arrDst, arrSrc, sizeof( arrSrc ) );
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这个程序中很明显存在内存损坏.

gcc编译器中有没有选项可以在编译时识别出这个问题?

注意:我用过valgrind --leak-check=full,但没有帮助.

Mat*_*Mat 7

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

海湾合作委员会可以认识其中一些.这通常需要启用优化(至少-01)和警告(-Wall,也添加-Wextra).

  • `-Wall`应该是默认值:-) (3认同)