Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this C++ code cause a memory leak (casting array new)

I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:

STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];

Later on however the memory is freed using a delete call:

delete pStruct;

Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead?

like image 969
Rob Avatar asked Sep 16 '08 14:09

Rob


1 Answers

Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.

More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.

Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:

delete [] (BYTE*) pStruct;
like image 156
Rob Walker Avatar answered Sep 21 '22 12:09

Rob Walker