According to C++17 [basic.compound]/3:
Every value of pointer type is one of the following:
- a pointer to an object or function (the pointer is said to point to the object or function), or
- a pointer past the end of an object (8.7), or
- the null pointer value (7.11) for that type, or
- an invalid pointer value.
The malloc
function returns a pointer value. Let us assume the call succeeded, so that the return value is not null. The specification of malloc
([c.malloc]) does not state that it creates any objects in the returned storage, so it seems like "invalid pointer value" is the least nonsensical category.
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void , use a type cast on the return value.
A NULL pointer doesn't allocate anything.
In layman's terms, a null pointer is a pointer to an address in the memory space that does not have a meaningful value and cannot be referenced by the calling program, for whatever reason. This will normally lead to an unhandled error, resulting in a segmentation fault.
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc().
That makes sense. It's an 'invalid pointer value' because it does not point to an object.
See later in that section, where it says:
A pointer value becomes invalid when the storage it denotes reaches the end of its storage duration
That implies that it's not the "value" of the pointer that makes it invalid, but rather that it does not point to a valid object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With