O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mismatched use of new and free or malloc and delete

These types of issues are rare but the possibility of them occurring can't be ruled out. It may so happen that when a legacy C-based tool is ported to C++, that some memory allocation is allocated by mistake but is freed up using the delete keyword or vice versa.

The following example demonstrates detecting the issue using Valgrind:

#include <stdlib.h>int main ( ) {        int *ptr = new int();        free (ptr); // The correct approach is delete ptr        char *c = (char*)malloc ( sizeof(char) );        delete c; // The correct approach is free ( c )        return 0;}

The following output demonstrates a Valgrind session that detects mismatched usage of free and delete:

g++ mismatchingnewandfree.cpp -gvalgrind ./a.out 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required