Search code examples
cpointersnullinitialization

Could an unitialized pointer be a NULL pointer?


From what I have read a NULL pointer points to the memory location "0" and an unitialized pointer points to a random location? Could it be that this random location sometimes is the "0" so that it is a NULL pointer as well? I realize that this will not happen all the time, but could it happen? Or has C some mechanism to stop it from happening?


Solution

  • Could an unitialized pointer be a NULL pointer?

    An uninitialized pointer could be a null pointer.

    (Do not use “NULL” for a null pointer. NULL is a specific macro defined by standard C headers with some different implications.)

    From what I have read a NULL pointer points to the memory location "0"…

    Many C implementations use memory address zero for null pointers, but this is not the only possibility. The C standard merely requires a null pointer to compare unequal to any object or function in the C program.

    … and an unitialized pointer points to a random location?

    No, “random” is a different concept. Saying something is random is asserting there is a lack of pattern or predictability to it. While it would not violate the C standard for an uninitialized object to behave randomly, the C standard does not say it does that, and it is unlikely that an uninitialized object would actually behave randomly rather than having at least some pattern of behavior arising out of the programming environment, although not a pattern controlled by the C standard.

    An uninitialized object is said to have an indeterminate value. An indeterminate value is not any particular value but is a description of how the object behaves. Effectively, it means the C standard does not require the object to have a determined value—in other words, the value is not fixed; it can appear to be different at different times—and does not require a C implementation to take the value from any particular place, including the memory reserved for the object.

    This means that, during optimization, a compiler may take the value of the object from memory, from a processor register, or anywhere else, and it may use different sources at different times, and other aspects of the program or the environment may change whatever source or sources the program is using for the value. So the value of the object in the program may appear to change.

    For example, if a is an uninitialized int, then printf("%d\n", a); printf("%d\n", a); could print two different numbers.

    Could it be that this random location sometimes is the "0" so that it is a NULL pointer as well?

    It can happen that the value used for an indeterminate pointer is a null pointer.