Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does malloc return an "invalid pointer value" in C++17? [duplicate]

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.

like image 918
Brian Bi Avatar asked Nov 26 '19 15:11

Brian Bi


People also ask

Does malloc return a pointer?

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.

Is memory allocated to NULL pointer?

A NULL pointer doesn't allocate anything.

WHAT IS NULL pointer in memory?

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.

Can you free malloc after return?

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().


1 Answers

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.

like image 58
Marshall Clow Avatar answered Oct 19 '22 03:10

Marshall Clow