| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
quick newbie question:
when do I delete pointers in destructors as opposed to simply setting them to NULL? Sometimes I (evidently wrongly) delete pointers and get the error message BLOCK_TYPE_IS_VALID(pHead->nBlocksUse) |
|
#2
|
|||
|
|||
|
Whenever you use the keyword new to allocate memory, somewhere in your code you should have a delete which counters it. By just setting your pointer to NULL in the destructor you will create a memory leak. It is good programming practice to place a safe check in your class destructors. eg.
if( pHead ) { delete pHead; pHead = NULL; } |
|
#3
|
||||
|
||||
|
Setting a pointer to NULL could be compared to "making it empty", the pointer now simply does not point anywhere.
Conversely, deleting the memory a pointer points to is freeing the memory from being restricted so that now it can be used by anything, this does not alter the pointer's value, however. Something fun to do, depending on your OS and compiler, is to allocate memory, fill it up, then deallocate it, and view what valus it has.... sometimes it's the same, sometimes it gets filled up in a microsecond by something else ![]()
__________________
Officially a member of the Itsacon fan club. Beer blasts are every friday at Viper_SB's house. I bring the chips. ![]() |
|
#4
|
|||
|
|||
|
Anyone deciding to try B-Con's "something fun to do" should be advised that it will probably cause your computer to crash as the program attempts to access memory that it no longer owns...
|
|
#5
|
||||
|
||||
|
Forgive me if I'm wrong but accessing memory outside of the program shouldn't cause a problem to the OS, as long as you don't change the value at the location you should be good
.Even if you do change the value and something does crash, you should only crash the program. Sadly this still might crash Windows .Take care, Mark. |
|
#6
|
||||
|
||||
|
Quote:
On the same note, another "fun" (but highly stupid) thing to do is to place a "ptr = new int;" line in an infinite loop, then go to the windows task manager and select the "view processes" tab and watch as the memory allocation for that program skyrockets, eventually causing the program to crash.... ah, the humor of a geek ![]() |
|
#7
|
|||
|
|||
|
"ah, the humor of a geek
"Is there any other kind? |
|
#8
|
||||
|
||||
|
Quote:
Hahaha I like it , will have to test some of these out just for kicks. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > deleting pointers |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|