Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
void *malloc(size_t);

Calling malloc( n s) allocates memory for an object whose size is n s and returns either a null pointer or a pointer to the allocated memory. A program can implicitly convert the pointer that malloc() returns into a different pointer type.

...

Code Block
bgColor#FFcccc
p = malloc(sizeof(gadget)); /* imminent problem */

quietly assigns p to point to storage too small for a widget. The subsequent assignments to p->i and p->d produce undefined behavior. They'll will most likely produce memory overruns.

...

Casting the result of malloc() to the appropriate pointer type enables the compiler to catch subsequent inadvertent pointer conversions. When allocating individual objects, the "appropriate pointer type" is a pointer to the type argument in the sizeof expression passed to malloc(), as in:

...

Code Block
bgColor#ccccff
enum { N = 16 };
widget *p;

/* ... */

p = MALLOC_ARRAY(N, widget);    /* OK */

Wiki Markup
A small collection of macros can provide secure implementations for common uses for the standard memory allocation functions.  The omission of a {{REALLOC()}} macro is intentional (see \[[MEM08-A. Use realloc() only to resize dynamically allocated arrays]]).

Code Block
bgColor#ccccff
/* allocates a single object using malloc(). */
#define MALLOC(type) ((type *)malloc(sizeof(type)))

/* allocates an array of objects using malloc(). */
#define MALLOC_ARRAY(number, type) \
    ((type *)malloc(number * sizeof(type)))

/* allocates a single object with a flexible array member using malloc(). */
#define MALLOC_FLEX(stype, number, etype) \
    ((stype *)malloc(sizeof(stype) + number * sizeof(etype)))

/* allocates an array of objects using calloc(). */
#define CALLOC(number, type) \
    ((type *)calloc(number, sizeof(type)))

/* reallocates an array of objects using realloc(). */
#define REALLOC_ARRAY(pointer, number, type) \
    ((type *)realloc(pointer, number * sizeof(type)))

/* reallocates a single object with a flexible array member using realloc(). */
#define REALLOC_FLEX(pointer, stype, number, etype) \
    ((stype *)realloc(pointer, sizeof(stype) + number * sizeof(etype)))

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory management functions"
\[[Summit 05|AA. C References#Summit 05]\] [Question 7.7|http://c-faq.com/malloc/cast.html], [Question 7.7b|http://c-faq.com/malloc/mallocnocast.html]

...