C++ – malloc: Invalid pointer dequeued from free list

c++mallocobjective-cpointersxcode

I have some C++ code in my OS X project that allocates an array thusly:

C * p = new C[lengthHint + 2];

This is in a template class; C is unsigned short. lengthHint is 1. This is all irrelevant. The error I get at runtime is:

malloc: *** error for object 0x60800000c4f0: Invalid pointer dequeued from free list
*** set a breakpoint in malloc_error_break to debug

It appears malloc is failing because a previous call to free freed something that wasn't valid. But it seems like free would've complained about that at the time.

Obviously there are millions of malloc/free and new/delete calls being executed and this same code is running without issues in other programs running on iOS and OS X. I'm not sure how to approach debugging this and am looking for suggestions.

Best Solution

As I suspected, the problem didn't had anything to do with the malloc call. I had decided to ignore the problem while I worked on another issue. The project was one where I was moving some code previously written in C++ for Windows over to Mac. While changing some type names I inadvertently changed this:

TCHAR * p = new TCHAR[(length + 1)];

to this:

char * p = new char(length + 1);

So just a typo, but one with pretty significant implications.

I discovered this while reviewing recent changes to a file that had some other odd behavior. So the answer to my original question was pretty simple and applies in a lot of other situations: "What have you changed lately?" :-)