[question][discussion] Re: Dangling pointers and undefined behavior: Does that mean there is no way to use realloc() without relying on undefined behavior?

Question

Regarding this discussion.

#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

216
FUZxxl•

The line p = new_p is never reached if realloc() 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.

1
fredmorcosOP•

The line p = new_p is never reached if realloc() fails. Undefined behaviour only occurs when the code that causes it is actually reached.

The problem is when realloc() succeeds, where p may or may not be live (provenance) anymore: https://www.reddit.com/r/C_Programming/comments/4ge2ci/dangling_pointers_and_undefined_behavior/d2hehd2

From 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 from p) is undefined behavior.

Am I reading too much into this? Or am I misunderstanding something? Or does "undefined behavior" here only apply to "reading" p but not "writing" to it?

PS: Please do not append [tags] to your post titles. We have flairs for that.

Sorry about that, I thought using [tag] would actually turn it into a flair. How can I directly use flairs?

1
FUZxxl•

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.

2
Rhomboid•

No, there is no need to invoke undefined behavior to use realloc().

Assigning to a pointer with indeterminate value is one of the few things that is always valid. Otherwise, pointers would be completely unusable, because you wouldn't be able to do something like this:

int *p;

p = malloc(...);
1
fredmorcosOP•

Well, that is exactly what I wanted to clarify... Here is my understanding from your example (with an extension):

int *p;

// p is now defined, *p is undefined

p = malloc(...);

// p and *p are defined

free(p);

// both p and *p become undefined here

That was my understanding from the linked article, discussion and that comment: https://www.reddit.com/r/C_Programming/comments/4ge2ci/dangling_pointers_and_undefined_behavior/d2hehd2

1
Rhomboid•

p has an indeterminate value after free(p). (But the same applies after int *p; so I don't see why you need to complicate things.) You can't do anything that attempts access the value of p, like if(p) or whatnot. But you can always assign to p. p = ... is always legal, because that's not accessing the indeterminate value, it's overwriting it.

3
fredmorcosOP•

That would make sense. Except that this post mentions otherwise: http://kristerw.blogspot.de/2016/04/dangling-pointers-and-undefined-behavior.html

The reason for the standard to make this undefined behavior is that even simple operations on dangling pointers, such as assignment or comparison, may misbehave and result in exceptions or arbitrary values on some architectures.

1
Rhomboid•

That refers to assigning the indeterminate value to something else, not assigning to a pointer that currently holds an indeterminate value;

int *a, *b;

a = b;

This is undefined behavior because of b, not because of a.

Again, this must be the case because even the simplest program in the world that uses pointers would invoke undefined behavior were it not so.

3
dmc_2930•

'p' is still a char * that lives on the stack. *p is undefined.

One thing I like to do is set pointers to NULL after they're freed:

free(p);
p = NULL;

This helps prevent the pointer from being accessed in the future without a crash, which can help the developer figure out what they did wrong.

1
dmc_2930•

p is still a pointer. It may be accessed all you want, you just can't dereference it.

"char *p" is in scope until the function returns.

1
fredmorcosOP•

I think there is a difference between scope and liveness (provenance?).

Take a look at the first example here: http://kristerw.blogspot.de/2016/04/dangling-pointers-and-undefined-behavior.html

void foo(int *p, int *q) {
    free(p);
    if (p == q)  // Undefined behavior!
        bar();
}

Also from the post:

The reason for the standard to make this undefined behavior is that even simple operations on dangling pointers, such as assignment or comparison, may misbehave and result in exceptions or arbitrary values on some architectures.

1
dmc_2930•

I agree that you should not use 'p' in a comparison after free. If you're going to compare two pointers, you should certainly do it before free'ing one of them.

1
fredmorcosOP•

What about the

such as assignment or comparison

part?

1
paulrpotts•

Sorry to jump in, but re: the "assignment" part:

Taking the example as my starting point:

char *str_p = "test string";
void foo(int *p, int *q) {
    free(p);
    p = str_p;
    printf( "%s", str_p );
}

I don't believe assigning p a new value after free(p) invokes undefined behavior.

I think the author of the blog post may mean that assigning the pointer p to another pointer could invoke undefined behavior, which would make sense. Even though the value of p has not changed, if the address is now "illegal" (has an invalid value, could trigger a hardware exception) because of some memory manager or segment register hardware constraint, copying the now illegal value into another pointer variable could trigger the same or similar kind of exception as comparing it.

2
OldWolf2•

Assignment does not use the old value of a variable, it only writes a new one. For example:

int x;
x = 5;   

is fine despite the fact that x did not have a value before the assignment.

Similarly, p = new_p; is always correct regardless of if p held a value and any properties of that value.

1