Re: "delete" causes prog to crash!

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Robby wrote:
I have declared a pointer on the heap (freeStoreMemory) as:

No, you have declared a pointer and initialised it with the address of an int from the heap.

int * pTempVal = new int;

I assign the pointer an address,

Where? How? Why? It already has a value -- the address of an integer you allocated on the heap.

> then I dereference it and all is fine!
However, in the book I am reading, they strongly suggest to delete your pointer so you free up the memory.

however when the program gets to the following line, the program crashes!

delete pTempVal;

Here is the error:

Debug assertion failed.....
_BLOCK_TYPE_IS_VALID(phead->nBlockUse)....
See C++ documentation....

Why does it react this way?

Because if you assign another value to the pointer you first obtained from 'new', you (a) lose the previous pointer and (b) probably attempt to 'delete' what was never allocated using 'new' in the first place.

> And the program compiles without errors or
warnings!

Undefined behaviour (like freeing memory you didn't obtain from 'new') never shows up at compile-time.

V
.



Relevant Pages

  • Re: "delete" causes prog to crash!
    ... use it to a pointer that points to the heap. ... and isn't a pointer supposed to hold the address of some data location. ... >> class codes ... >> int returnCode() const; ...
    (microsoft.public.vc.language)
  • Re: "delete" causes prog to crash!
    ... int codes::returnCodeconst ... >> I have declared a pointer on the heap as: ... > an int from the heap. ...
    (microsoft.public.vc.language)
  • Re: Neatest way to get the end pointer?
    ... And you invoke undefined behavior. ... as a pointer 'index' compared against an int * iterator. ... One byte beyond is fine (though you can't dereference it), ...
    (comp.lang.c)
  • Re: Pointer assigning.
    ... element) to the object pointed to by ptr2. ... int *ptr2 = NULL; ... want to - we were mistaken in adding a dereference operator). ... All we want is to assign a pointer value to ptr2. ...
    (comp.lang.c)
  • Re: link pointer access problem
    ... int b_value; ... be a null pointer ... dereference a pointer with an indeterminate value. ...
    (comp.lang.c)