cpointersscope

I don't understand the behavior of a pointer


I'm in a formation and we're seeing pointers. We're facing a mystery :

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

int main()
{
    short *p_var = 0;
    
    if (p_var == NULL) {
        short var = 123;
        p_var = &var;
        printf("ma variable= %d \n", *p_var);
    }
    printf("ma variable= %d \n", *p_var);

    return 0;
}

As you can see, the purpose of this function is to show some problems about pointers like scope or null errors. Here, the good result is 123 and 0, shown by the printf but other mates have 123 and 123. We work on the same IDE and we use the same compiler.

Do you have any idea of what happens ?


Solution

  • There is no good behavior for this code: the behavior of the second printf is undefined.

    The pointer is set inside the if block to point to a variable defined in this scope, var which is set to 123. The behavior of the first printf is fully defined and indeed prints ma variable= 123 .

    When control leaves this block, variable var goes out of scope and its location may be used for some other purpose... or not.

    Accessing this memory via a pointer has undefined behavior. It may produce the value 123 on some machines, another value such as 0 on others and crash on more exotic architectures. The behavior can change from one compiler to another, with different compiler options, with different operating systems, or even just different times... nothing can be predicted about it, the behavior is undefined.

    Your teacher is well advised introducing the concept of invalid pointers and such, but they should say that any behavior for this code is good or expected. Ask them to explain undefined behavior for which this piece of code and your experience is a good illustration.