Search code examples
cpointersrealloc

Validity of the realloc() function in C


Is

pointer = (int*)realloc(0, sizeof(int))

a valid expression?

I feel that since the first argument to realloc is a pointer and here it is 0(memory address reserved for the OS), this statement should not be a valid one. Can someone comment on the validity of the statement?


Solution

  • It is valid statement.

    §7.22.3.5 from the C standard:

    void *realloc(void *ptr, size_t size);
    

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.