What is the difference between a null pointer and a stray pointer?
Answer: When you delete a pointer, you tell the compiler to free the memory, but the pointer itself continues to exist. It is now a stray pointer. When you then write myPtr = 0; you change it from being a stray pointer to being a null pointer. Normally, if you delete a pointer and then delete it again, your program is undefined. That is, anything might happen—if you are lucky, the program will crash. If you delete a null pointer, nothing happens; it is safe. Using a stray or a null pointer (for example, writing myPtr = 5;) is illegal, and it might crash. If the pointer is null, it will crash, another benefit of null over stray. Predictable crashes are preferred because they are easier to debug
Answer: When you delete a pointer, you tell the compiler to free the memory, but the pointer itself continues to exist. It is now a stray pointer. When you then write myPtr = 0; you change it from being a stray pointer to being a null pointer. Normally, if you delete a pointer and then delete it again, your program is undefined. That is, anything might happen—if you are lucky, the program will crash. If you delete a null pointer, nothing happens; it is safe. Using a stray or a null pointer (for example, writing myPtr = 5;) is illegal, and it might crash. If the pointer is null, it will crash, another benefit of null over stray. Predictable crashes are preferred because they are easier to debug
'프로그래밍 > C++' 카테고리의 다른 글
[에러] jump to case label -fpermissive (0) | 2014.02.19 |
---|---|
[template]템플릿 예제 (0) | 2013.08.04 |
[c++] malloc/free 대신 new/delete을 쓰는 이유? (0) | 2013.05.18 |
[c++]c에서 c++ 함수 호출에 대한 의문 (0) | 2013.05.11 |
[c++] expected unqualified-id before string constant (0) | 2013.05.11 |