rhuala, on 12 Feb 2013 - 18:49, said:
int i, a[10];
for(i=0;i<15;i++)
a[i]=i;
That's not a memory leak. That's a buffer overrun. You can avoid it by not using magic numbers:
const size_t ARRAY_LENGTH = 10; //or whatever
int ary[ARRAY_LENGTH];
for(int i=0; i < ARRAY_LENGTH; ++i) {
ary[i] = i;
} Quote
One technique I use to track them down or errors in general is I write a for loop to a high number say 100,000 then I keep calling that function. If it has a memory leak it will usually crash or I examine Task Manager-> Performance and watch the Free Memory shrink.
No bueno. This will only catch leaks that always happen, and it's too hard to distinguish from normal allocation behavior if leaks are small. Use a utility like VLD instead, and use smart pointers and RAII to make leakage a non-issue.
Quote
Another one, that I think causes a crash:
BitBlt(hdc, -5, -5 , 100 , 100, hdcPic, 0, 0, SRCCOPY);
When using GDI, does blitting outside the screen resolution cause a memory leak?
No. It clips the blit according to the target context.
You're confused about what a memory leak is, or at least about what causes them.
This is a memory leak:
int main() {
int* derp = new int;
return 0;
}
This is a harmless one, but it's a leak because memory is allocated and not freed. You avoid memory leaks by strictly following proper memory management practices like RAII.
The examples you gave were concerning buffer overrun behavior. You avoid overruns by limiting buffer actions by always implementing bounds checking. Write loops in such a way that they are made aware of - and are unable to pass beyond - the end of the buffer, etc. Use the secure CRT functions rather than the original ones.
ProvenDantheman, on 12 Feb 2013 - 18:59, said:
Also, make sure you only call delete once, or if there is a possible instance of you calling delete twice, set the variable to NULL when you delete it. Deleting a NULL pointer has no effect.
Obscuring a bug is not the same as fixing a bug. Your program should always be aware of its allocations and react intelligently. NULL deletion has its uses but abusing it to avoid implementing allocation control is like taking aspirin instead of going to the hospital after cutting your arm off.
Edited by Khatharr, 12 February 2013 - 09:53 PM.