2
#include <stdio.h>
#include <stdlib.h>

void changeAddressofPtr(int ** ptr);

int main()
{
    int num = 12;
    int * numptr = &num;//num pointer points to num variable

    printf("%d\n",*numptr);   //just a check
    changeAddressofPtr(&numptr);  //send address of pointer to be able to change it
    printf("%d",*numptr);  //check value after changing

    return 0;
}

void changeAddressofPtr(int ** ptr)
{
    int newNum = 8;
    *ptr = &newNum;  //make main's pointer point to newNum
}

I was trying this out and expected an error or some wrong garbage value printed in the second printf() but this is the output:

12
8 //Value of variable I thought would be deleted
  • 1
    This just means it hasn't been overwritten yet. Don't rely on this behavior. – Carcigenicate Oct 20 '17 at 11:35
  • 6
    You're invoking *undefined behavior* - anything can happen in this code – UnholySheep Oct 20 '17 at 11:35
  • 2
    Just because a variable goes out of scope doesn't mean the memory it occupied cease to exist. – Some programmer dude Oct 20 '17 at 11:35
  • Add another call to printf before the last one. – Costantino Grana Oct 20 '17 at 11:37
  • 1
    For the behaviour to be different, the memory would have to be actively cleared (making C programs slower than necessary), or overwritten (you were lucky). – DevSolar Oct 20 '17 at 11:37
  • Ahh didn't realize this is undefined behavior, I thought it would throw an error and was confused when it worked. – BareWithImANoob Oct 20 '17 at 11:41
  • Before or after calling the function, and why? @CostantinoGrana – BareWithImANoob Oct 20 '17 at 11:43
  • 1
    @BareWithImANoob never expect this in C ... there are no runtime errors defined. An error that doesn't violate a constraint (= is still compilable code) is always just invoking undefined behavior. –  Oct 20 '17 at 11:43
  • @FelixPalmen Well, it is easy to bloat simple facts to pages of text, the real art is brevity here. I like the answer of "Charles Brunet" or even "msw" in the duplicate. There is a reason why there is an _upper_ instead a lower limit on for example theses. Eric Lipperts answer goes well over the target here in my eyes ;) – Ctx Oct 20 '17 at 11:46
  • @FelixPalmen I opened the answer you sent but just to check is c and c++ identical in this aspect? – BareWithImANoob Oct 20 '17 at 11:47
  • 1
    @Ctx **most** people (obviously not the OP here) asking questions like this here didn't grasp yet what *undefined behavior* means and for those, this answer is perfect ... giving a nudge to adjust their logical thinking. But this discussion is off-topic here anyways. –  Oct 20 '17 at 11:47
  • @BareWithImANoob Mostly. C++ has exceptions, so there can be some "runtime errors" thrown. But those aside, programming errors lead to undefined behavior in C++ as well. –  Oct 20 '17 at 11:49
  • Okay, thanks a lot for the help and the link @FelixPalmen – BareWithImANoob Oct 20 '17 at 11:55

0 Answers0