Saturday, November 10, 2007

Tips for memory management!!

1. For C/C++

a. Forget to delete an object.


int* x;
x = new int();
x = y; (2) <<<< leak memory here

Because the memory referenced by x is now no longer referenced by x after we execute statement 2.

b.Create an array but only delete one object;
Solution: Use delete[] to delete an array instead of delete

c. Delete object twice:
int *x;
int *y;

x = new int();
y = x;

...Do sth...
delete x;
...Do sth...
delete y;

--> crash here.

d. Create an object in dll but delete it outside dll. The correct way is call the function which delete object in dll. Dll should provide the way to delete object in its process.

e. Always check the array boundary before access it or you will be crashed and program will have the buffer overflow.

No comments: