tags:

views:

209

answers:

5

Hello, When,i try to assign null value to my pointer,it sometimes crashes on that line. The code is something like this :

if(s_counter != NULL)
{
    delete s_counter;
    s_counter = NULL; // it sometimes crashes here.
}

This is not reproducable,100%,but it occurs frequently. Can anybody help in this?

+6  A: 

Probably the line is off by one and it crashes in the delete.

starblue
But,whenever it crashes,it shows this line. So,i think it is a little improbable,that the line is off everytime.
Ajay
When debuggers show the wrong source line, they usually do so consistently (at least until you change the code). The debug info does not change between runs.
Steve Jessop
+3  A: 

Note that although it is OK to delete a NULL pointer, it is not necessarily OK to delete a a non-NULL pointer. The pointer must have been allocated with new and must not already have been deleted. Note also that allocating NULL to deleted pointers can add to a false sense of security - simply checking for NULL is not enough, your programs memory allocation semantics need to be correct too.

anon
+2  A: 

I suspect that you are double-deleting. This has all sorts of strange effects. Set a break point on the delete and look at the object there before deleting. Does it look valid? Another way is to set the breakpoint on the delete and make sure you only get there once.

Steve Rowe
+2  A: 

Here's what springs to my mind:

  • Make sure s_counter is initialized to NULL (or better 0 in C++) before any allocation, this will ensure you'll never attempt to delete garbage (and crash).
  • If s_counter is part of an object, then the object may have been deleted.
  • If s_counter is a static as its name seems to imply, the fact that you can't reproduce it reliably could be caused by a race condition, check your thread access patterns.
bltxd
I am also feeling,that it is a race conditions. Thanks,will debug more.
Ajay
A: 

One other thing that could happen is if your s_counter pointer is pointing to an array of objects instead of a single object. In that case you should use delete[] instead of delete . If you use delete on an array of objects then the memory will be corrupted and all sorts of strange things might start to happen.

Naveen