Question

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?

Was it helpful?

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.

OTHER TIPS

Per C 2011 6.3.2.3 3, 0 may be used as a null pointer constant:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

In the call to realloc, the 0 argument is automatically converted to the type of the parameter, void *, per 6.5.2.2 7:

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type.

From man realloc:

If ptr is NULL, then the call is equivalent to mal‐ loc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), cal‐ loc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

In summary, its equivalent to malloc() when 1st parameter is NULL, so valid statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top