by hatsunearu · 10y ago · 0 comments
This is why it's considered bad form to cast the result of malloc in C. Of course, modern compilers will warn about implicit prototypes, and as of C99 it's no longer legal.
https://nickdesaulniers.github.io/blog/2016/05/30/data-model...
% uname -a
FreeBSD 10.1-RELEASE FreeBSD 10.1-RELEASE #0 r274401: Tue Nov 11 21:02:49 UTC 2014 root@releng1.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC amd64
% gcc -o foo foo.c
foo.c: In function 'main':
foo.c:4:17: warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]
p = (int*)malloc(sizeof(int)); ^
% ./foo
%
This is with GCC 4.8.5In the older C standard (C89), the code has undefined behaviour because implicit declaration of the function malloc is not compatible with its definition in the standard library. It is a futile task to try to define the undefined.