Uninitialized pointers in code

后端 未结 8 2284
旧巷少年郎
旧巷少年郎 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:38

    It's alway better to initialize a pointer to NULL if for any reason you can't initialize it while declaration occurs . For example:

    Object *ptr = new Object();
    

    Typically a function can check the value of the pointer against NULL to verify that the pointer has been initialized before. If you haven't set it explicitly to NULL, and it points to a random value, then it could be dereferenced causing a segfault.

提交回复
热议问题