Memory leak, how to find?

1
2
3
4
5
6
7
8
9
void main()
{
    int *pi = new int(0x12345678);
    int *pAry = new int[10];
    delete pi;
    delete []pAry;

    return;
}


If, written
1
2
 delete []pi;
 delete pAry;

or
delete [] pi;
or
delete pAry;

How could I known whether and how much memory leak?
There's no way to know it from inside the program. There are memory debuggers capable of detecting and measuring memory leaks, and some system monitors report how much memory a program is using. You can use one to find when a program is using more memory than it should.
If, written
1
2
delete []pi;
delete pAry; 


Undefined behavior. I don't understand that part of the question.

What exactly do you mean by a 'memory leak'? The memory not being deleted properly?
1
2
3
4
5
6
7
8
9
10
void main()
{
    int *pi = new int(0x12345678);
    int *pAry = new int[10];
    delete pi;
    
    return;
    // Here, memory leak.Because we need 'delete []pAry'.
    // How can I found it here automatically?
}
Don't use void main. Main returns int.

If you want to "find a memory leak" I suggest using a debugger. But you shouldn't need to.
Just delete the dynamic memory you used when you don't need it anymore... that's all a memory leak is.

"A memory leak in computer science is a particular type of unintentional memory consumption by a computer program where the program fails to release memory when no longer needed"

When you don't need a dynamically allocated variable anymore, delete it. Or use a garbage collection algorithm, but I don't know anything about that.
Microsoft's MFC has a debug_new that's mapped into debug builds.

Each allocation is recorded and tied up with frees. At the end of the program run, the program lists allocations, the first few bytes of the buffer, the file and line number where the allocation occurred. It's pretty cool.
Topic archived. No new replies allowed.