Versions Compared

Key

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

...

The result of calling malloc(0) to allocate 0 bytes is implementation defined. In this example, a dynamic array of integers is allocated to store size elements. However, if size is 0, the call to malloc(size) may return a reference to a block of memory of size 0 instead of a null pointer. When (nonempty) data is copied to this location, a heap-buffer overflow occurs.

Code Block
bgColor#FFcccc
langc
size_t size;

/* initialize size, possibly by user-controlled input */

int *list = (int *)malloc(size);
if (list == NULL) {
  /* Handle allocation error */
}
else {
/* Continue processing list */
}

...

To ensure that zero is never passed as a size argument to malloc(), size is checked to ensure it has a positive value.

Code Block
bgColor#ccccff
langc
size_t size;

/* initialize size, possibly by user-controlled input */

if (size == 0) {
  /* Handle error */
}
int *list = (int *)malloc(size);
if (list == NULL) {
  /* Handle allocation error */
}
/* Continue processing list */

...

The realloc() function deallocates the old object and returns a pointer to a new object of a specified size. If memory for the new object cannot be allocated, the realloc() function does not deallocate the old object and its value is unchanged. If the realloc() function returns NULL, failing to free the original memory will result in a memory leak. As a result, the following idiom is often recommended for reallocating memory:

Code Block
bgColor#FFcccc
langc
size_t nsize = /* some value, possibly user supplied */;
char *p2;
char *p = (char *)malloc(100);
if (p == NULL) {
  /* Handle error */
}

/* ... */

if ((p2 = (char *)realloc(p, nsize)) == NULL) {
  free(p);
  p = NULL;
  return NULL;
}
p = p2;

...

This compliant solution does not pass a size argument of zero to the realloc() function.

Code Block
bgColor#ccccff
langc
size_t nsize;
/* initialize nsize */
char *p2;
char *p = (char *)malloc(100);
if (p == NULL) {
  /* Handle error */
}

/* ... */

p2 = NULL;
if (nsize != 0) {
  p2 = (char *)realloc(p, nsize);
}
if (p2 == NULL) {
  free(p);
  p = NULL;
  return NULL;
}
p = p2;

...