0

If you declare a pointer in C and don't give it a NULL value, then is that pointer's memory address still reserved AKA it can't be taken over by no data till you give it a real value or NUll value. This got me thinking. Thank you in advance:)

PuuRaidur
  • 3
  • 2
  • 1
    How is this different from declaring an, lets say, `int` and not initializing it to anything? – tkausl Jul 02 '22 at 14:39
  • What does "it can't be taken over by no data" mean? – Cheatah Jul 02 '22 at 14:51
  • 2
    Yes, an uninitialized pointer variable points to some unpredictable place, but *no*, let me say that again, **no**, the memory at that unpredictable place is *not* reserved for you! Quite the opposite. You might also be interested in [this answer](https://stackoverflow.com/questions/37087286/c-program-crashes-when-adding-an-extra-int/37087465#37087465). – Steve Summit Jul 02 '22 at 14:55

1 Answers1

1

If any variable is left uninitialized, and it is not declared at file scope or with the static qualifier, its value is indeterminate. If a variable with an indeterminate value is read, and if that variable never has its address taken, then attempting to do so triggers undefined behavior.

In practice, this means it could hold any value, and that value need not be the same on subsequent reads. On some architectures it could even be a trap representation, where just reading the value can cause a crash.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • What do you mean under file scope? – PuuRaidur Jul 03 '22 at 19:21
  • @PuuRaidur "file scope" means at the top-level of a file, i.e. outside of any function. – dbush Jul 03 '22 at 19:47
  • so does pointer with no value reserve a memory address then or not? you're talking about values, but i am talking about memory addresses – PuuRaidur Jul 03 '22 at 20:37
  • @PuuRaidur All variables have an address that is valid during their lifetime, whether the variable was initialized or not. – dbush Jul 03 '22 at 20:42
  • yeah but if pointer has no value then every time it picks soke random memory address as its own memory, but if its value is NULL then it always points to same memory address, right? – PuuRaidur Jul 03 '22 at 20:49
  • @PuuRaidur You're confusing the address of a pointer variable with the value of a pointer which is also an address. The address of the pointer variable is fixed and valid. The *value* of that pointer value if uninitialized is (in practice) some random address that may or may not be valid. – dbush Jul 03 '22 at 20:52
  • you're right i just tested it myself with code. But turns out that if you initialize pointer's value as NULL then it simply doesn't point anywhere. Not that I am trying to weave or something of course. Thanks my fellow C brother – PuuRaidur Jul 03 '22 at 20:57