Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a C pointer point to a value in an inner block and dereference the pointer after the block ends?

I’m wondering if a C pointer can point to a value in an inner block and then dereference the pointer after the inner block ends?

#include <stdio.h>

int main() {
    int a = 42;
    int *r;
    {
        int b = 43;
        r = &b;
    }
    int c = 44;
    printf("%d\n", c);  // Output: 44

    // Is this OK?
    printf("%d\n", *r); // Output: 43
    return 0;
}

Am I getting the output "43" by luck or by design? Does C language specification say something about this situation? (Note that I’m not asking what a specific C compiler behaves)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is not allowed. You were "lucky" you got an output of 43.

The lifetime of b ends after the scope it which it was declared ended, and accessing a variable whose lifetime has ended triggers undefined behavior.

This is described in section 6.2.4p2 of the C language:

The lifetime of an object is the portion of program execution during
which storage is guaranteed to be reserved for it. An object exists,
has a constant address, and retains its last-stored value
throughout its lifetime. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading