4

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?

3
  • 2
    Please read about it. Why do you think it would be defined or undefined? Where is your research effort? What did you find which you did not understand? Adding those makes it a good question, no offense. Commented Sep 11, 2017 at 6:09
  • You only invoke potentially poorly-defined behavior when you access the value of a variable that has not been initialized. Commented Sep 11, 2017 at 6:48
  • Could you please explain what you mean with "Before dereferenced ptr, i have assigned 10 to ptr and dereferenced it." ? Assigning 10to *ptr(not ptris dereferencing. You dereference it before you dereference it? Commented Sep 11, 2017 at 7:25

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

(though the compiler may still optimize these as if, as the pointer is never passed around anywhere)
@AnttiHaapala - Yeah, it certainly may. The behavior of the code still remains will defined either way, however.
2

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

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

x =10

Comments

1

To my understanding it is defined behaviour, as it it not necessary to have memory initialized before writing to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.