...
In the following noncompliant code example, if malloc()
is not declared, either explicitly, or by including stdlib.h
, a compiler may implicitly declare malloc()
as int malloc()
. (Compilers that only comply with C90 are required to provide an implicit declaration of malloc()
.) If the platform's size of int
is 32 bits, but the size of pointers is 64 bits, the resulting pointer could be truncated as a result of the implicit declaration of malloc()
returning a 32-bit integer.
Code Block | ||||
---|---|---|---|---|
| ||||
/* #include <stdlib.h> is missing */ int main(void) { size_t i; for (i = 0; i < 100; ++i) { char *ptr = (char*)malloc(0x10000000); /* int malloc() assumed */ *ptr = 'a'; } return 0; } |
When compiled with Microsoft Visual Studio (a C90-only platform), the above code will eventually cause an access violation when dereferencing ptr
in the loop.
Compliant Solution (Implicit Function Declaration)
In this This compliant solution , declares malloc()
is explicitly declared before it is used by including the appropriate header file.
Code Block | ||||
---|---|---|---|---|
| ||||
void *malloc(size_t size);#include <stdlib.h> int main(void) { size_t i; for (i = 0; i < 100; ++i) { char *ptr = (char*)malloc(0x10000000); /* int malloc() assumed */ *ptr = 'a'; } return 0; } |
For more information on function declarations, see see DCL07-C. Include the appropriate type information in function declarators.
Compliant Solution (Implicit Function Declaration)
This compliant solution declares malloc()
by including the appropriate header file.
...
bgColor | #ccccff |
---|---|
lang | c |
...
Noncompliant Code Example (Implicit Return Type)
...