1

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?

Ludricio
  • 156
  • 16
Amad27
  • 151
  • 1
  • 1
  • 8
  • 2
    You didn't assign `NULL` to `null_test`. – Jabberwocky Jan 16 '17 at 07:09
  • All you need is `int *null_test = 0;` – Alex P. Jan 16 '17 at 07:11
  • `int x` defines an `int`. An `int` cannot be `NULL` by definition. Just a pointer can be `NULL`. – alk Jan 16 '17 at 07:13
  • @Amad27 I would suggest reading [this answer](http://stackoverflow.com/a/11965368/6527069) to help understand just WHY uninitialized variables can give undefined behavior. – Ludricio Jan 16 '17 at 07:21
  • The variable in question actualle _is_ very well initialized. `null_test` has a value assigned. Only `*null_test` is uninitialized – Gerhardh Jan 16 '17 at 07:25
  • 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? – Gerhardh Jan 16 '17 at 07:30
  • 3
    The address of a valid variable is always a valid pointer, so null_test points to a valid memory address. – xaxxon Jan 16 '17 at 07:31
  • @LudvigRydahl Deleting your last comment makes our responses pointless. Nevertheless the initial comment still makes an incorrect reference to UB. – Gerhardh Jan 16 '17 at 09:03

2 Answers2

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
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;

artm
  • 17,291
  • 6
  • 38
  • 54