Problem of using malloc() without including stdlib.h (original) (raw)

Kelly O'Hair kelly.ohair at oracle.com
Wed Jan 18 16:26:42 UTC 2012


On Jan 18, 2012, at 12:19 AM, Jonathan Lu wrote:

Hi core-libs-dev,

I found that for some native code of OpenJDK code base, malloc() is used without including header file stdlib.h, such as following files, ./src/solaris/native/sun/java2d/opengl/GLXSurfaceData.c ./src/solaris/native/sun/java2d/x11/XRBackendNative.c .... I assume that there's no hacking tricks involved here, right? because this may cause problem for some C compilers, which assumes 'int' as the default return type of a function if it cannot find the function's declaration during compiling. Under such a condition, actual return result of type 'void*' from malloc() will be converted to 'int', which may result in truncated pointers in 64bit platforms. If the application tries to dereference such a broken pointer, error will occur. Indeed I found some indirect includes of stdlib.h, but there're still some I do not see a stdlib.h get included from any of the direct/indirect included headers. I think in order to fix this problem, two approaches may be considered here, a) add "#include <stdlib.h>" to every missing .c file. b) add "#include <stdlib.h>" to a commonly referenced header file, such as jniutil.h. but it would not be easy to find such a file for all and creating one is the same as approach a).

I suggest a) It should be harmless and is the right thing to do.

It's been a while since I studied the C standard, but I vaguely recall that there was another standard C include file that would cause the malloc() prototype declaration to show up. Or maybe it wasn't a standard one. In any case, I think your a) approach is correct and I don't see much a need for detailed discussions on this, as long as it builds correctly with no warnings on all platforms. It should be fine and correct. That's my 2 cents.

-kto

But both methods need to change many files, any other ideas about how to fix it more elegantly?

Thanks and best regards! - Jonathan



More information about the core-libs-dev mailing list