...
MEM02-EX1: Do not immediately cast the results of malloc()
when compiling as C90 or earlier because for code that will be compiled using a C90 conforming compiler because it is possible for the cast to hide a bug in platforms defect. This may happen, for example, in implementations where pointers are larger than intsthe size of an int
.
For In the following example, if stdlib.h
is not properly included, compilers will implicitly declare malloc()
as int malloc(int)
. If the size of int
on the platform is 32 bits, but the size of a pointer is 64 bits, the resulting pointer could be truncated due to the as a result of the implicit declaration of malloc()
returning a 32-bit integer.
Code Block | ||||
---|---|---|---|---|
| ||||
/* #include <stdlib.h> is missing */ int main(void) { intsize_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, the above code will eventually cause an access violation when dereferencing ptr
in the loop. Note that this code also does not fails to comply with DCL31-C. Declare identifiers before using them by using an implicit declaration of malloc()
.
...