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 s size elements. However, if s size is zero, the call to malloc(ssize) may return a reference to a block of memory of size 0 rather than NULL. When data is copied to this location, a heap-buffer overflow occurs.

Code Block
bgColor#FFcccc
/* ... */
list = malloc(sizeof(int) * s)size);
if (list == NULL) {
  /* Handle Allocation Error */
}
/* Continue Processing list */
/* ... */

Compliant Code Example

...

To ensure that zero is never passed as a size argument to {{malloc()}}, a check must be made on {{s}} to ensure it is not zero. Note that this solution checks for numeric overflow \[[INT32-C. Ensure that integer operations do not result in an overflow]\].on size to ensure it is not zero.

Code Block
bgColor#ccccff

if (ssize <== 0) {
  /* Handle Error */
}
if (sizeof(int) > SIZE_MAX/s) {
   /* handle overflow */
}
list = malloc(sizeof(int) * ssize);
if (list == NULL) {
  /* Handle Allocation Error */
}
/* Continue Processing list */
/* ... */

...