Matthew O'Flynn
Matthew O'Flynn

Reputation: 123

How can I demonstrate that delete does not deallocate all memory new [] allocates?

I want to write a simple application that proves that a memory leak exists if you use delete on a pointer that was allocated using new [].

I am currently using the CRT Debug library to monitor the memory in my application to capture the memory after allocation and after the improper deallocation. Please see my test code here:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <memory>

using namespace std;

int main()
{ 
    _CrtMemState s1, s2, mem_diff;

    // Allocate 40 bytes of memory.
    int *leak = new int[10];

    // Capture the memory state after the allocation.
    _CrtMemCheckpoint(&s1);

    // Deallocate that memory with incorrect delete operator.    
    delete leak;

    // Capture and compare the memory after the deallocation.
    _CrtMemCheckpoint(&s2);
    _CrtMemDifference(&mem_diff, &s1, &s2);
    _CrtMemDumpStatistics(&mem_diff);

    return 0;
}

However, in my debug output I'm see that all 40 bytes are being deallocated. This is the output from my debug console in Visual Studio 2015 Express:

0 bytes in 0 Free Blocks.
-40 bytes in -1 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 0 bytes.

My other idea for why this is working is that it's undefined behaviour and is compiler specific behaviour in this case.

Upvotes: 0

Views: 350

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275600

void leak_via_wrong_delete() {
  std::vector<int>* buff = new std::vector<int>[1000];
  for (auto i = 0; i < 1000; ++i)
    buff[i].resize(i * 1000);
  delete buff;
}

Wrap this with your leak detection code.

In practice, the real reason why delete[] is important is that it calls the destructor of all of the elements in the array, in most implementations I know of. (There may be one medium-obscure platform where it also fails catastrophically, I cannot recall).

For classes without trivial destruction, they store the number of elements (or something similar) in the bytes before the start of the allocated array. Then delete[] examines it and destroys each object in turn.

Upvotes: 1

Related Questions