This piece of code :
char buff[255];
memcpy(buff,0,255);
The compiler doesn't give any warning during compilation but the process fails with a segmentation fault But when I compile the following code
char buff[255];
memcpy(buff,2,255);
The compiler gives the following warning
warning: passing argument 2 of 'memcpy' makes pointer from integer without a cast [enabled by default]
Why does compiler not give an warning for the constant 0 I am using GCC version 4.7.2
Also is there some compiler flag that will give warnings for such code
0
is implicitly converted to the null pointer when used in a pointer context. 2
isn't implicitly converted to a pointer type, hence the warning.
You can read more at the comp.lang.c
FAQ, section 5, specifically Question 5.2.
In a quick test here, neither GCC nor Clang warned about the 0
case (without extra flags), but the clang static analyzer does:
example.c:6:4: warning: Null pointer argument in call to memory copy function
memcpy(buff,0,255);
^~~~~~~~~~~~~~~~~~
/usr/include/secure/_string.h:55:6: note: expanded from macro 'memcpy'
? __builtin___memcpy_chk (dest, src, len, __darwin_obsz0 (dest)) \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
As has been mentioned elsewhere in comments here, GCC will warn if you pass -Wnonnull
(also included with -Wall
):
$ gcc -Wnonnull example.c -o example
example.c: In function ‘main’:
example.c:6: warning: null argument where non-null required (argument 2)