realloc(p, 0)

C

copx

Is realloc(p, 0) a valid operation or does it cause undefined behaviour?
Can you still free(p) after this?
Even if it's valid do you think compiler writers actually thought of this
case?
 
P

Peter Nilsson

copx said:
Is realloc(p, 0) a valid operation

Yes.

"If size is zero and ptr is not a null pointer, the object
it points to is freed."

Use a reference like N869 if you don't have the standard.
or does it cause undefined behaviour?
Can you still free(p) after this?
No.

Even if it's valid do you think compiler writers actually
thought of this case?

No, but standard library authors _must_, if they want to claim
compliance.
 
C

copx

Peter Nilsson said:
Yes.

"If size is zero and ptr is not a null pointer, the object
it points to is freed."

Use a reference like N869 if you don't have the standard.


No, but standard library authors _must_, if they want to claim
compliance.

Thanks for the info!

copx
 
K

Keith Thompson

Christopher Benson-Manica said:

That depends on how you invoke it.

If you just call

realloc(p, 0);

and ignore the returned value, p will be a pointer to deallocated
memory, and free(p) (or any ues of p) will invoke undefined behavior.

If you call it like this:

p = realloc(p, 0);

then the value of p will be either a null pointer or a valid pointer;
in either case, you can safely call free(p).
 
C

Christopher Benson-Manica

Keith Thompson said:
That depends on how you invoke it.

True; I just figured OP was asking about the case where you can't,
since he didn't seem to be checking the return value of realloc().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top