0

What happen I write malloc((size_t)NULL) for dynamic memory allocation in C?

int main()
{
    char *ptr = malloc((size_t)NULL);
}

Is it allocate memory in heap section? or Is it undefined behavior?

msc
  • 33,420
  • 29
  • 119
  • 214

2 Answers2

4

What happen I write malloc(NULL)..

Wait, stop, you do not write malloc(NULL), why would you?

The argument to malloc() is the "size" of the memory expected, that is not supposed to be a null pointer constant.

Quoting C11, chapter §7.22.3.4, (emphasis mine)

void *malloc(size_t size);

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

That said, for most cases, NULL is represented by integer constant value 0, so malloc(NULL) is equivalent to malloc(0), which again is implementation defined behavior.

Quoting chapter §7.22.3./P1

[...] If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

This allocates the amount of memory defined by the constant NULL. If NULL == 0, then behavior is implementation defined.

Erki Aring
  • 2,032
  • 13
  • 15