Question

I am opening an audio file to read it and I get an abandoned malloc block from this caller each time.

In a loop I set data like this (which is marked as the memory usage in instruments as 99.7%) data = (short*)malloc(kSegmentSize*sizeof(short));

and free it like this free(data); at the end of each iteration.

Im not really sure what is happening here and would appreciate any help.

EDIT: KSegmentSize varies in the thousands, from minimum 6000 - max 50000 (speculative)

Instruments trace:

enter image description here

enter image description here

Was it helpful?

Solution 3

Sorry to answer my own question, but after commenting out code back up the stack trace the actual issue was to do with the file not be disposed.

Calling ExtAudioFileDispose(audioFile); solved this hidden bug. Instruments was not entirely clear and marked mallocs as the leak. To be fair the mallocs where from data that was within the file referenced by the ExtAudioOpenFile method, not disposing the file reference left a leak.

OTHER TIPS

Not having the exact code:

Pretty sure you're having this problem b/c something between the malloc and free is throwing (and you're probably catching it already so you don't exit the loop). Depending on if this is happening in C (or objective-C) or C++ code, you have slightly different methods of resolution.

In C++, wrap the malloc/free in the RAII pattern so that when the stack is unwound the free is called.

class MyData {
public:
    A(size_t numShorts) : dataPtr(0) { dataPtr = malloc(numShorts * sizeof(short)); }
    ~A() { free(dataPtr); }
    operator short*() { return dataPtr; }
private:
    short* dataPtr;
}

MyData data(numShorts);
// do your stuff, you can still use data as you were before due the 'operator short*'
// allow the dtor to be called when you go out of scope

In Objective-C you need to use a finally block:

void* myPtr = 0;
@try { myPtr = malloc(...); }
@catch {}
@finally { free(myPtr); }

Suggest that you start by simplifying, for example comment out (preferably using #if 0) all of the code except the malloc/free. Run the code and ensure no abandoned heap blocks. Then gradually re-introduce the remaining code and re-run until you hit the problem, then debug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top