Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: moved exception code to DCL31-C

...

MEM02-EX1: Do not immediately cast the results of malloc() for code that will be compiled using a C90 conforming compiler because it is possible for the cast to hide a defect.  This may happen, for example, in implementations where pointers are larger than the size of an int.  

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 as a result of the implicit declaration of malloc() returning a 32-bit integer.

Code Block
bgColor#FFcccc
langc
/* #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, the above code will eventually cause an access violation when dereferencing ptr in the loop.  Note that this code also fails to comply with more critical defect.  See DCL31-C. Declare identifiers before using them by using an implicit declaration of  for a code example that uses malloc() without first declaring it.

Risk Assessment

Failing to cast the result of a memory allocation function call into a pointer to the allocated type can result in inadvertent pointer conversions. Code that follows this recommendation will compile and execute equally well in C++.

...