c++cpointersaddress-operator

Address of operator can initlize a pointer but the fill-in value is garbage


Pointers to uninitialized memory will causing error. Deference such pointer represents a invalid address.

int *pi;                                                                                                                                                          
printf("%i\n",*pi);  

The above code leads to the using uninitialized variable Error.

error: ‘pi’ is used uninitialized in this function

However, when printing the address first, seems the pointer is initialized by a valid address but filled in with invalid data

int *pi; 
printf("%p\n",&pi); //address printing                                                                                                                                                       
printf("%i\n",*pi); 

which prints out:

0x7ffeea9313c8 //valid virtual address
-125990072 //invalid data

Question:

Does the address of operator (&) initialize a pointer? If not, please correct the wrong understandings.


Solution

  • Because you pass the address of this pointer to a function, compiler can no longer tell whether it has been initialized inside that function.

    Consider the following function:

    void init_ptr(int **ptr) { *ptr = some_valid_addr; }
    

    Then you call:

    int *pi; 
    init_ptr(&pi);
    

    You know printf() won't init the pointer, but compiler doesn't have enough information to tell the difference.