联系
Knight's Tale » 技术

Pointer Bad Usage Example: Memory Leak!

2011-03-30 17:01

When we use C++ pointer, we should save the pointer and the original pointer should not be thrown away in our program.

A bad usage example about C++ pointer is :

 int a = new int;
    a = 2;
    int b = *a;
    delete &b;
We have a pointer "a", we assign its value to object "b" and we throw away the pointer "a". And we delete object "b" when we want to release the memory what pointer "a" has allocated.

However, we will meet "Memory Leak" error when we want to release(delete) object "b",( we want to release pointer "a" , but this pointer is lost. We will release object "b" because pointer is assigned to object "b".)

Another wrong usage example is :

we use stack, and push object to it:

std::stack< int > myStack;
int a = new int;
myStack.push(a);
Then we will want to release the memory what we have allocated:
int a = &myStack.top();
delete a;
myStack.pop();
The right usage is:
std::stack < int > myStack;
int a = new int;
myStack.push(a);
int *a = myStack.top();
delete a;
myStack.pop();
Conclusion:

So, when we write C++ pointer code, we should not throw away the original pointer and delete this pointer when we want to release the memory.