...
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 zero, the call to malloc(size)
may return a reference to a block of memory of size 0 rather than NULL
instead of a{{ null pointer}}. When data is copied to this location, a heap-buffer overflow occurs.
...
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 | ||
---|---|---|
| ||
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 */
|
...