memory leak(c++)

Maret 19, 2009 at 4:54 AM (C/C++)

Honestly, it’s about my college home works. In an attempt to maniplate your computer memory with pointer, you have to prevent it happen(memory leak). It happen when a memory is being useless. Let’s make this simple: You have an allocated memory but nobody(I mean pointer(s)) access that address.

Look at this sample:

int *P;
//allocating an amount of memory space and save that address in pointer P
P = new int;
*P = 13;

P = new int;
*P = 25;

Look at this sample. At first you allocate some memory space and you give that memory a value. Until that time, It has no memory leak. But, after you allocate new memory space and save it in same pointer,  the previous address you have allocated isn’t accessed by any pointers. Nobody(again.. it’s pointer) Access that address, and it become a waste.

You can polish that memory leak with deallocate command after if you don’t need that address anymore.

int *P;
//allocate an amount of memory space and save that address in pointer P
P = new int;
*P = 13;

//deallocate address saved in its pointer
delete P;

P = new int;
*P = 25;

Happy to code!!

Tulis sebuah Komentar