0

I was purposely trying to get a NULL pointer in C but I failed to do this. Here is what I was coding:

int main(void) {
  int x; //UNINITIALIZED so that it will represent "nothing"
  int *null_test = &x;
  printf("This should be null   %p \n", null_test);
}

But it gave me an address: 0x7fd96c300020 which doesnt seem to be NULL as I was hoping.

Why? I didn't even initializex but still not null?

8
  • 2
    You didn't assign NULL to null_test. Commented Jan 16, 2017 at 7:09
  • All you need is int *null_test = 0; Commented Jan 16, 2017 at 7:11
  • int x defines an int. An int cannot be NULL by definition. Just a pointer can be NULL. Commented Jan 16, 2017 at 7:13
  • 2
    @LudvigRydahl x is not a pointer. How could it point anywhere? It has a specific location, (probably on the stack) which of course can contain garbage. But the value of x is not read anywhere. Neither directly, nor via null_test. Is taking the address without reading from it undefined behaviour? Commented Jan 16, 2017 at 7:30
  • 3
    The address of a valid variable is always a valid pointer, so null_test points to a valid memory address. Commented Jan 16, 2017 at 7:31

2 Answers 2

9

After

int *null_test = &x;

null_test contains the address of x. This address is independent of the content of x even if x has never been initialized.

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

Comments

5

Why? I didn't even initializex but still not null?

You need to differentiate between 1) definition and 2) initialisation. A variable is defined when the memory is allocated to it. A variable is initialised when that memory location is filled in with some value.

Here x is uninitialised but already defined - that means being allocated - that means x has a specific location in memory. And so &x is not NULL and so null_test:

int *null_test = &x;

If you want null_test to be NULL, just assign it explicitly

int *null_test = NULL;

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.