Uninitialized pointers in code

后端 未结 8 2183
旧巷少年郎
旧巷少年郎 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.

    0 讨论(0)
  • 2020-11-30 03:56

    In C++, you should generally avoid plain old pointers altogether. Standard library classes, smart pointers (until C++0x only in various libraries like Boost or Loki) and references can and should be used in most places instead.

    If you can't avoid pointers, it's indeed preferable to declare them with initializations, which in most cases should not be NULL, but the actual target value, because in C++ you can mix declarations and expressions freely, so you can and should only declare the variable at the point you have meaningful value for it.

    That's not the case with C where you have to use pointers a lot and all variables have to (or had to before C99; I am not exactly sure) be declared at the begining of a scope. So many people still have bad habits from C that are not appropriate for C++.

    0 讨论(0)
提交回复
热议问题