Hacker News new | ask | show | jobs
by wat10000 10 days ago

  int *x = malloc(4);
  *x = 42;
  int *y = realloc(x, 4);
  *y = 43;
  printf(“%p %d %p %d\n”, x, *x, y, *y);
This may well print the same address for x and y while printing different values for x and y. Despite having the same bitwise value, x was invalidated by the call to realloc and it became illegal to access x. Thus the compiler is free to assume that x still holds the value previously assigned to it (or make demons fly out of your nose when you try to read from it), because a pointer isn’t just a memory address, it has meaning tied to where you got it and what you did with it.
1 comments

Isn't the proper sane default behavior to fault if x is accessed after realloc?
That certainly would be very nice. It’s also extremely difficult to do reliably. One certainly could make the argument that it should be done in easy cases like this example. But I suspect that the cases where it’s easy to consistently fault and the cases where it’s a useful diagnostic in real programs don’t have much overlap.
To do that you need to track more information than the integer-like value of pointer x.

In this case there’s a good chance that x and y have the same value, for example.

So that is more costly in storage and speed.

I think that depends on compiler flags, at least with gcc.