Deleting the same pointer twice in C++
I have taken up C++ programming for learning software programming. I have just began learning it from the last month. I am already confused with alot of concepts in it. One such concept is Pointers. Although I am in the process of learning it can anyone detail me on Pointers? and more importantly What happens if we delete the same pointer twice ?
Re: Deleting the same pointer twice in C++
Even I am not that good with C++ programming because I am also in the process of learning it. But I can help you with definition of pointer. A pointer in C++ is said to point to the memory location which is stored in it. In other words, a pointer variable contains the memory address where the actual object can be found. In C++ while defining pointers we have also specify the type of variable to which it is pointing.
.
Re: Deleting the same pointer twice in C++
Code:
class xyz
{
.
.
.
};
void disp()
{
xyz* X = new xyz();
delete X; // first delete
delete X; // second delete
.
.
.
}
Consider the above code,
The second delete X is capable of generating unwanted consequences . This includes crashing your program, corrupting your heap, making bizare and unwanted changes to obkects that are already existing on heap, etc. So hence in C++, never Delete a Pointer twice as the pointer is reletad to a memory location directly.
Re: Deleting the same pointer twice in C++
When you delete the pointer, it still points to the same place - the only difference is that the place was marked as "free" in some system-specific way. This memory location is free and now might be allocated for some other data. Deleting it second time might be problematic as it's no longer free. The second call to delete will probably try to mark it as "free" again. Thus with the second delete the memory location on heap that you are deleting is now been used by some othe object data. Never try to do this in C++.
Re: Deleting the same pointer twice in C++
hey can u explain me heap concept related to memory management.........:rolleyes:
Re: Deleting the same pointer twice in C++
The heap is reserved for the memory allocation needs of the program. It is an area apart from the program code and the stack. Typical C programs use the functions malloc and free to allocate and deallocate heap memory. The Debug version of MFC provides modified versions of the C++ built-in operators new and delete to allocate and deallocate objects in heap memory.
More information can be found here.
Re: Deleting the same pointer twice in C++
Thanks for the info......:thumbup1: