[question][discussion] Re: Dangling pointers and undefined behavior: Does that mean there is no way to use realloc() without relying on undefined behavior?
#include <stdlib.h>
int main (void) {
char *p, *new_p;
p = malloc(20);
new_p = realloc(p, 40);
if (new_p == NULL) {
free(p);
return 1; /* fail */
}
p = new_p; /* accessing p may be undefined behavior? */
free(p);
return 0;
}
Is assignment to p relying on undefined behavior, since the value of p may or may not be live?
Posted May 12, 2016, 10:34 AM UTC
The line
p = new_pis never reached ifrealloc()fails. Undefined behaviour only occurs when the code that causes it is actually reached.PS: Please do not append [tags] to your post titles. We have flairs for that.
The problem is when realloc() succeeds, where
pmay or may not be live (provenance) anymore: https://www.reddit.com/r/C_Programming/comments/4ge2ci/dangling_pointers_and_undefined_behavior/d2hehd2From the linked article in the linked thread, and the comment I linked, it seems like any access to
p(or any other variable that has been assigned to fromp) is undefined behavior.Am I reading too much into this? Or am I misunderstanding something? Or does "undefined behavior" here only apply to "reading"
pbut not "writing" to it?Sorry about that, I thought using [tag] would actually turn it into a flair. How can I directly use flairs?
If you write to a variable, it's value is not used. Therefore, no undefined behaviour occurs when you overwrite a variable containing an indeterminste value, such as a pointer to released memory.