Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer points to uninitialized variable

In the following program, ptr points to uninitialized variable x. Before printing ptr, I have assigned 10 to ptr and print it.

#include <stdio.h>

int main()
{
    int *ptr;
    int x;

    ptr = &x;
    *ptr = 10;

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

Both ptr and x print the correct value. But, I have doubt, Is it defined behavior?

like image 955
Jayesh Avatar asked Dec 04 '22 21:12

Jayesh


2 Answers

Yes, it is. You assign a valid value to ptr and then use indirection to assign a valid value to x.

The address of a variable like x and its value are separate things. After storage is allocated, taking the address is always well defined, regardless of the value in the variable.

like image 110
StoryTeller - Unslander Monica Avatar answered Dec 17 '22 11:12

StoryTeller - Unslander Monica


Yes , because when you declare x the placeholder / memory will become available for you .

ptr = &x; *ptr = 10; code effectively means

x =10

like image 23
WorkaroundNewbie Avatar answered Dec 17 '22 12:12

WorkaroundNewbie