0

I have this maybe weird question. I was considering following example where I pass a pointer by reference so if I change the pointer address of the argument the initial pointer should also change the address. And indeed this happens. However the value of a in the main method will have some random value and not 3 as the q variable inside changePointer whose address we use to change pointer a to.

Is there something stupid oversee or is the whole thing just undefined behaviour.

#include <iostream>

void changePointer(int* &p) {
  int q = 3;
  std::cout << "Address of q: " << &q << std::endl;
  p = &q;
  std::cout << "Value of p: " << *p << std::endl;
}

int main() {
  int* a = new int(4);
  changePointer(a);
  std::cout << "Adress of a: " << a << std::endl;
  std::cout << "Value of a: " << *a << std::endl;

}
Philipp
  • 2,376
  • 5
  • 29
  • 47
  • 1
    `q` is scoped variable, it gets destroyed when `changePointer` returns => `a` then points to freed memory => `a` is invalid pointer => `*a` is Undefined Behavior. Write `delete p; p = new int(3)` and `delete `p` in `main`. – GingerPlusPlus Nov 29 '15 at 13:01
  • Ah right, this makes sense. Thanks – Philipp Nov 29 '15 at 13:02
  • It's also duplicate of [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable), [returning a local variable from function in C](http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c) – GingerPlusPlus Nov 29 '15 at 13:16

3 Answers3

3

This is undefined behavior because you access a local variable which is already vanished.

Try adding static before int q = 3; and making the variable static so that the variable won't vanish on returning from the function.

Also, please do not cause memory leak by allocating some buffer to a and throwing it away!

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

q is a local variable inside changePointer, so when changePointer exits the address of q contains garbage.

JSF
  • 5,281
  • 1
  • 13
  • 20
1

q is scoped variable, it gets destroyed when changePointer returns. a then points to freed memory, so it's invalid pointer, and dereferencing it (*a) is Undefined Behavior.

Corrected code:

void changePointer(int* &p) {
  int* q = new int(3); // this way q lives until you delete it
  std::cout << "Address of q: " << q << std::endl;
  delete p; // we don't want unfreeable memory
  p = q;
  std::cout << "Value of p: " << *p << std::endl;
}

int main() {
  int* a = new int(4);
  changePointer(a);
  std::cout << "Adress of a: " << a << std::endl;
  std::cout << "Value of a: " << *a << std::endl;
  delete a;
}
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52