Next: , Previous: Example 6, Up: Examples

16.7 Incompatible function calls

This example illustrates how the mpatrol library checks for calls to incompatible pairs of memory allocation functions. It requires the use of C++, although does not use any C++ features except for overloaded operators. The source is in tests/fail/test7.c, and tests/fail/test8.c is similar.

     23  /*
     24   * Allocates a block of 16 bytes using C++ operator new[] and then
     25   * attempts to free it using C++ operator delete.
     26   */
     29  #include "mpatrol.h"
     32  int main(void)
     33  {
     34      char *p;
     36      p = new char[16];
     37      delete p;
     38      return EXIT_SUCCESS;
     39  }

The relevant parts of mpatrol.log are shown below.

     ALLOC: operator new[] (74, 16 bytes, 4 bytes) [int main()|test7.c|36]
             0x0804955D main+13
             0x400DB9CB __libc_start_main+255
             0x080494C1 _start+33
     returns 0x08062FC0
     FREE: operator delete (0x08062FC0) [int main()|test7.c|37]
             0x0804956E main+30
             0x400DB9CB __libc_start_main+255
             0x080494C1 _start+33
     ERROR: [INCOMP]: operator delete: 0x08062FC0 was allocated with operator new[]
         0x08062FC0 (16 bytes) {operator new[]:74:0} [int main()|test7.c|36]
             0x0804955D main+13
             0x400DB9CB __libc_start_main+255
             0x080494C1 _start+33

This shows a call to operator new[], closely followed by a call to operator delete. However, in C++ calls to operator new[] must be matched by calls to operator delete[] and not operator delete. Hence, the library reports this as an error and does not free the memory allocation.