-1

As I've understood from the answers to this related question, an uninitialized pointer can contain pretty much anything and could therefore also happen to equal to NULL. Is there a way to distinguish uninitialized pointers from null pointers, for example by giving them a specific value?

For example, consider:

// could potentially print
FILE *f1;
if (f1 == NULL)
    fprintf(stderr, "f1 is NULL");

// will never print, but is this a good/safe way?
FILE *f2 = -1;
if (f2 == NULL)
    fprintf(stderr, "f2 is NULL");
domsson
  • 4,553
  • 2
  • 22
  • 40
  • 5
    If you worry about using uninitialized local variables, then *explicitly initialize them*. That's the only safe solution. And for pointers the only safe "not a valid pointer" value is `NULL`. – Some programmer dude Jul 07 '18 at 11:24
  • @Someprogrammerdude What if I want to pass an uninitialized ptr to a function BUT have that be optional? Using `NULL` to signal that the argument should not be used is not an option, but if the function is supposed to initialize the ptr for me in any other case? I assume I need an entirely different approach? – domsson Jul 07 '18 at 11:29
  • Then you need to come up with another abstraction, wrapping the "optional" values using structures or functions that are designed to handle "uninitialized" data. I put "uninitialized" in quotes because the data can't really *be* uninitialized, the API or structure need to have an initialized flag that tells if the wrapped real data is initialized or not. – Some programmer dude Jul 07 '18 at 11:31
  • Gotcha. Thanks for clarifying. – domsson Jul 07 '18 at 11:31
  • 1
    If you want your function to initialize the pointer, `NULL` is fine to mark the absence of a value because in every other case you'd have to pass the address of the pointer: `f(&ptr)` vs. `f(NULL)`. If you didn't pass `&ptr`, `f` could not modify `ptr`. – melpomene Jul 07 '18 at 11:40
  • @melpomene Ah, of course! I guess one can tell that I'm quite new to C still. – domsson Jul 07 '18 at 12:12

1 Answers1

2

You can't.

An uninitialised value could be anything. An uninitialised pointer could point anywhere. It could even point to valid data by sheer coincidence.

Initialise your pointers to NULL or a real value; if you ever find yourself seeing uninitialised values then a programmer somewhere has done something wrong.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62