0

I would like to discuss the following code:

#include <stdio.h>

int main () {

    int i;
    int * ptr ;

    for ( i = 0; i < 3; ++i ){
        int tmp = 1;
        ptr = &tmp;
    }

    printf ("%d\n", *ptr);

    return 0;
}

As far as I know, a new variable tmp is created and then destroyed every time the for cycle is executed. As a consequence, at the end the pointer ptr could no more refer a priori to a memory area which contain the integer value 1 (since it may happen that it had been erased, or overwritten by new data). On the other hand, I executed that code many times on many systems, and it always worked. Question: is it basically a coincidence due to the operating system / compiler in use? Is it generally wrong to expect *ptr to be 1, right?

My apologies for the easy question, but I am sure an answer will allow me to better understand why a more complex code I have written does not work and produce a segmentation fault error (compared to the code in this post, it is the same of relying on having the pointer ptr always "well-defined").

Siguza
  • 21,155
  • 6
  • 52
  • 89
  • 3
    It's undefined behavior Using a pointer to a variable that is out of scope is incorrect. – Retired Ninja Aug 21 '16 at 17:09
  • 1
    You cannot conclude the correctness of a C program from just running it. You need to check the source code and verify that it follows the language rules. – Kerrek SB Aug 21 '16 at 17:13
  • 1
    From he C11 Standard (draft): "*6.2.4/2 [...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.*" – alk Aug 21 '16 at 17:17
  • Thanks a lot for the clarification. –  Aug 21 '16 at 17:26

1 Answers1

0

First : Your understanding is correct

2nd: Try using the code in release version with compiler optimisations flag on. In all probability you'll get a core dump

Its also possible that since your code is very small, the run time memory you access is actually belongs to your executable. This piece of code in a big program / in a library should crash immediately.

Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36