Alex Rivera | Logout

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

Asked 2008-09-16T14:47:22.913
10

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?

Edit
Report

2 Answers

7

I personally think you'd be better off using std::vector to manage your memory, so you don't need the delete.

std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);
STRUCT* pStruct = (STRUCT*)(&backing[0]);

Once backing leaves scope, your pStruct is no longer valid.

Or, you can use:

boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);
STRUCT* pStruct = (STRUCT*)backing.get();

Or boost::shared_array if you need to move ownership around.

answered 2008-09-16T15:39:51.323
2

If you really must do this sort of thing, you should probably call operator new directly:

STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);

I believe calling it this way avoids calling constructors/destructors.

answered 2008-09-16T16:20:14.643

Your Answer