Uninitialized pointers in code

后端 未结 8 2307
旧巷少年郎
旧巷少年郎 2020-11-30 03:15

I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some othe

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 03:54

    The line:

    int* ptr;
    

    is definitely not guaranteed to initialize the pointer value to anything in particular. The line:

    int* ptr = NULL;
    

    Will initialize the pointer to point to address zero, which in practice will never hold anything useful, and which will be conventionally checked for as an invalid pointer value.

    Of course, it is still possible, as has been said by Doug T., to attempt to use this pointer without checking it and so it would crash all the same.

    Explicitly initializing to NULL has the advantage of ensuring that dereferencing the pointer before setting it to something useful will crash, which is actually a good thing, because it prevents the code from "accidentally" working while masking a serious bug.

提交回复
热议问题