iPhone memory leak (a lot of allocations) - iphone

I tested my app in Instruments. No leaks found, but app crashes (not immediately - after ~20 minutes [depends on user's activity] of working). I viewed Allocations. It reports:
Category | Live Bytes | Count Live | # Living | # Transitory | Overall Bytes | # Allocations (Net / Overall)
Malloc 16 Bytes | 235088 | 14693 | 0 | 235088 | 14693 | 1.00
All records (when I view detailed info for "Malloc 16 Bytes") are made for only one object:
# | Object Address | Category | Creation Time | Live | Size | Responsible Library | Responsible Caller
0 | 0x104b50 | 817461248 | • | dyld | _dyld_start
(...and 14693 records with same fields data, except, of course, #).
Stack Trace:
0 CoreFoundation __CFAllocatorSystemAllocate
1 CoreFoundation CFAllocatorAllocate
2 CoreFoundation __CFGetConverter
3 CoreFoundation CFStringEncodingGetConverter
4 CoreFoundation CFStringGetSystemEncoding
5 CoreFoundation __CFStringInitializeSystemEncoding
6 CoreFoundation __CFInitialize
7 dyld ImageLoaderMachO::doImageInit(ImageLoader::LinkContext const&)
8 dyld ImageLoaderMachO::doInitialization(ImageLoader::LinkContext const&)
9 dyld ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&)
10 dyld ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&)
11 dyld ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&)
12 dyld dyld::initializeMainExecutable()
13 dyld dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**)
14 dyld dyldbootstrap::start(macho_header const*, int, char const**, long, macho_header const*)
15 dyld _dyld_start
I can't paste all code here (app is not a few lines). But, please, give me some advice - where to search for memory leak or smth. else...

IMHO, your number one priority is to let your application run. Try to locate where the problem is, by commenting part of your code; if the app doesn't crash anymore, then the problem is located within the part you just commented, if it still crashes, then it must be somewhere else. Repeat the steps until you fix the bug.
After you get your app run, then you can start to find its leak or improve performance.

Related

NSBundle loading crashes in Release

I'm facing a really strange behavior in an iPad App. I create several bundles, the app downloads them an saves them to the documents directory.
I have a custom bundle manager where i can load the bundles like this.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *bundlePath;
if (![bundleName hasSuffix:#".bundle"]) {
bundlePath = [documentsDirectory stringByAppendingFormat:#"/%#.bundle", bundleName];
} else {
bundlePath = [documentsDirectory stringByAppendingFormat:#"/%#", bundleName];
}
NSBundle *bundle = nil;
NSError *error = nil;
bundle = [[NSBundle alloc] initWithPath:bundlePath];
if (!bundle) {
return nil;
}
[bundle loadAndReturnError:&error];
In debug mode all code works like a charm. The bundle gets loaded and the content can be used in the app. The bundles contain images and nibs, no code. In the bundle build settings I've set COMBINE_HIDPI_IMAGES to NO, so that the images will not be combined as tiff images. The bundles also do not contain any code.
So what's the problem. Well when starting the app without debugging (not connected to Xcode) the app crashes and generates this error message. [bundle loadAndReturnError:&error] is where the code crashes.
Exception Type: EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 dyld 0x2fe8e2d8 strcmp + 0
1 dyld 0x2fe83aac ImageLoaderMachO::parseLoadCmds() + 56
2 dyld 0x2fe88d30 ImageLoaderMachOCompressed::instantiateFromFile(char const*, int, unsigned char const*, unsigned long long, unsigned long long, stat const&, unsigned int, unsigned int, linkedit_data_command const*, ImageLoader::LinkContext const&) + 296
3 dyld 0x2fe839c6 ImageLoaderMachO::instantiateFromFile(char const*, int, unsigned char const*, unsigned long long, unsigned long long, stat const&, ImageLoader::LinkContext const&) + 222
4 dyld 0x2fe7b0d4 dyld::loadPhase6(int, stat const&, char const*, dyld::LoadContext const&) + 664
5 dyld 0x2fe7e774 dyld::loadPhase5stat(char const*, dyld::LoadContext const&, stat*, int*, bool*, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 428
6 dyld 0x2fe7e498 dyld::loadPhase5(char const*, char const*, dyld::LoadContext const&, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 248
7 dyld 0x2fe7e37c dyld::loadPhase4(char const*, char const*, dyld::LoadContext const&, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 128
8 dyld 0x2fe7e29c dyld::loadPhase3(char const*, char const*, dyld::LoadContext const&, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 984
9 dyld 0x2fe7dc36 dyld::loadPhase1(char const*, char const*, dyld::LoadContext const&, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 110
10 dyld 0x2fe7ada4 dyld::loadPhase0(char const*, char const*, dyld::LoadContext const&, std::__1::vector<char const*, std::__1::allocator<char const*> >*) + 168
11 dyld 0x2fe7ab58 dyld::load(char const*, dyld::LoadContext const&) + 208
12 dyld 0x2fe7f8da dlopen + 802
13 libdyld.dylib 0x39dee946 dlopen + 46
14 CoreFoundation 0x31ab4910 _CFBundleDlfcnLoadBundle + 128
15 CoreFoundation 0x31ab478c _CFBundleLoadExecutableAndReturnError + 356
16 Foundation 0x323d2154 -[NSBundle loadAndReturnError:] + 844
17 Visitor Self Service 0x000e251a -[CoreBundleManager bundleForName:] (CoreBundleManager.m:70)
18 Visitor Self Service 0x000cd418 -[CoreProcessDefinition processBundle] (CoreProcessDefinition.m:226)
19 Visitor Self Service 0x000cf17e -[CoreProcessRuntime loadControllerForStep:] (CoreProcessRuntime.m:187)
20 Visitor Self Service 0x000ce9f4 -[CoreProcessRuntime performNextStepInProcessDefinition] (CoreProcessRuntime.m:112)
21 Visitor Self Service 0x000ba642 __62-[DynamicViewController prepareControllerForProcessDefinition]_block_invoke (DynamicViewController.m:107)
22 libdispatch.dylib 0x39ddb790 _dispatch_call_block_and_release + 8
23 libdispatch.dylib 0x39dde8be _dispatch_after_timer_callback + 10
24 libdispatch.dylib 0x39ddb5d8 _dispatch_client_callout + 20
25 libdispatch.dylib 0x39ddc48a _dispatch_source_invoke + 254
26 libdispatch.dylib 0x39ddee04 _dispatch_main_queue_callback_4CF + 164
27 CoreFoundation 0x31afb1ac __CFRunLoopRun + 1284
28 CoreFoundation 0x31a6e238 CFRunLoopRunSpecific + 352
29 CoreFoundation 0x31a6e0c4 CFRunLoopRunInMode + 100
30 GraphicsServices 0x35629336 GSEventRunModal + 70
31 UIKit 0x3398a2b4 UIApplicationMain + 1116
32 Visitor Self Service 0x000b66d8 main (main.m:16)
33 libdyld.dylib 0x39deeb1c start + 0
Finally I got it working.
There are several steps for setting up a proper bundle.
In the Project Build Settings for the Bundle set
Architectures => armv7, armv7s
Supported Plattforms => iOS
Valid Architectures => armv7, armv7s
Set up a valid Code Sign Identity
Set up a matching provisioning profile
You also need a Info.plist
Required Device Capabilities => armv7, armv7s
Principal Class => Your bundles principal class name
Executable File => Same as Principal Class
Note
External code execution is prohibited by the Apple Review Guidelines, so it's only possible in In-House Apps.
2.7 Apps that download code in any way or form will be rejected
2.8 Apps that install or launch other executable code will be rejected

iOS crash at startup without Xcode attached

I'm having a strange issue with an iOS app of mine. When it is run via Xcode (Build & Run), all works well. The app launches and everything works as expected.
However, if I try to open the app by tapping its icon as the user would (via Springboard), the app crashes immediately with the crashlog below. It seems to point to some kind of an image-releated issue, but I don't understand how it doesn't occur when debugging using Xcode.
Can anyone shed some light?
Date/Time: 2012-06-15 16:13:29.035 +0100
OS Version: iPhone OS 5.1.1 (9B206)
Report Version: 104
Exception Type: EXC_CRASH (SIGKILL)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 dyld 0x2fe76464 strcmp + 0
1 dyld 0x2fe6a6e2 ImageLoaderMachO::parseLoadCmds() + 54
2 dyld 0x2fe72058 ImageLoaderMachOCompressed::instantiateFromFile(char const*, int, unsigned char const*, unsigned long long, unsigned long long, stat const&, unsigned int, unsigned int, linkedit_data_command const*, ImageLoader::LinkContext const&) + 296
3 dyld 0x2fe6b23a ImageLoaderMachO::instantiateFromFile(char const*, int, unsigned char const*, unsigned long long, unsigned long long, stat const&, ImageLoader::LinkContext const&) + 302
4 dyld 0x2fe622f6 _ZN4dyldL10loadPhase6EiRK4statPKcRKNS_11LoadContextE + 478
5 dyld 0x2fe6255e _ZN4dyldL14loadPhase5statEPKcRKNS_11LoadContextEP4statPiPbPSt6vectorIS1_SaIS1_EE + 386
6 dyld 0x2fe62716 _ZN4dyldL10loadPhase5EPKcS1_RKNS_11LoadContextEPSt6vectorIS1_SaIS1_EE + 278
7 dyld 0x2fe628fe _ZN4dyldL10loadPhase4EPKcS1_RKNS_11LoadContextEPSt6vectorIS1_SaIS1_EE + 218
8 dyld 0x2fe630dc _ZN4dyldL10loadPhase3EPKcS1_RKNS_11LoadContextEPSt6vectorIS1_SaIS1_EE + 1144
9 dyld 0x2fe63240 _ZN4dyldL10loadPhase1EPKcS1_RKNS_11LoadContextEPSt6vectorIS1_SaIS1_EE + 108
10 dyld 0x2fe63392 _ZN4dyldL10loadPhase0EPKcS1_RKNS_11LoadContextEPSt6vectorIS1_SaIS1_EE + 262
11 dyld 0x2fe634c4 dyld::load(char const*, dyld::LoadContext const&) + 224
12 dyld 0x2fe650f2 dlopen + 742
13 libdyld.dylib 0x360d55a2 dlopen + 42
14 CoreFoundation 0x37256092 _CFBundleDlfcnLoadBundle + 106
15 CoreFoundation 0x37255f36 _CFBundleLoadExecutableAndReturnError + 370
16 Foundation 0x32d7bf40 -[NSBundle loadAndReturnError:] + 904
17 SomeApp 0x000bcb3a 0x5e000 + 387898
18 SomeApp 0x000c56d0 0x5e000 + 423632
19 SomeApp 0x000c539a 0x5e000 + 422810
20 SomeApp 0x00062f86 0x5e000 + 20358
21 UIKit 0x30438c84 -[UIViewController view] + 160
22 SomeApp 0x000622a6 0x5e000 + 17062
23 SomeApp 0x0005fcc4 0x5e000 + 7364
24 UIKit 0x30437ca4 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1176
25 UIKit 0x304317d6 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 402
26 UIKit 0x303ffabc -[UIApplication handleEvent:withNewEvent:] + 1004
27 UIKit 0x303ff560 -[UIApplication sendEvent:] + 48
28 UIKit 0x303fef34 _UIApplicationHandleEvent + 5820
29 GraphicsServices 0x3741b224 PurpleEventCallback + 876
30 CoreFoundation 0x3729f51c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
31 CoreFoundation 0x3729f4be __CFRunLoopDoSource1 + 134
32 CoreFoundation 0x3729e30c __CFRunLoopRun + 1364
33 CoreFoundation 0x3722149e CFRunLoopRunSpecific + 294
34 CoreFoundation 0x37221366 CFRunLoopRunInMode + 98
35 UIKit 0x30430864 -[UIApplication _run] + 544
36 UIKit 0x3042dcce UIApplicationMain + 1074
37 SomeApp 0x0005fb00 0x5e000 + 6912
38 SomeApp 0x0005fac0 0x5e000 + 6848
Edit: Talked this through with the Apple Developer Team. The issue is that I used a self-made plugin in my app that wasn't codesigned (even though I told Xcode to do so). However, Xcode 4.3.3 has a bug that breaks codesigning for bundles, so we'll see how this works out soon.
It looks like this is still a problem as of Xcode 4.5. As a workaround, it seems that you can force the build to sign the bundle.
Adding the following as a final "Run Script" build phase for the bundle fixed it for me:
codesign -fs "iPhone Developer" ${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}
Your application may be taking too long to launch. It is given unlimited time when launching from Xcode, but is not afforded this luxury when launching from SpringBoard.
Take a look at this for reference: https://developer.apple.com/library/ios/#qa/qa2009/qa1592.html
edit: Oh, how did I get here... this is two weeks old.

iOS 5.0 Simulator always quits: "The simulated application quit"

I'm using Xcode 4.2 final Build 4D199 from the Mac App Store. When I want to start any application in the iOS 5 simulator it quits telling me that i can Quit, Switch SDK or Relaunch. I downloaded additionally the 4.3 SDK/Simulator and there it works. I used the builts for iOS 5 during beta but finally removed every other developer installation using uninstall-devtools in /Developer/Library but it didn't solve the problem.
Console says:
Process: SpringBoard [4764]
Path: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/System/Library/CoreServices/SpringBoard.app/SpringBoard
Identifier: SpringBoard
Version: ??? (???)
Code Type: X86 (Native)
Parent Process: iPhone Simulator [4748]
Date/Time: 2011-10-31 14:45:25.541 +0100
OS Version: Mac OS X 10.7.2 (11C74)
Report Version: 9
Crashed Thread: 6
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: 0x000000000000000a, 0x000000000bf33000
VM Regions Near 0xbf33000:
__LINKEDIT 000000000bf29000-000000000bf33000 [ 40K] r--/rwx SM=COW /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib
--> mapped file 000000000bf33000-000000000bf42000 [ 60K] r--/r-x SM=PRV /Network/*/*.cpbitmap
__TEXT 000000000bf42000-000000000bf8f000 [ 308K] r-x/rwx SM=COW /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib
Application Specific Information:
iPhone Simulator 272, iPhone OS 5.0 (iPhone/9A334)
Thread 6 Crashed:
0 QuartzCore 0x01ce06b5 void CA::OGL::SW::image_sampler<CA::OGL::SW::Format::ARGB8_Host, false, false, false, false>(CA::OGL::SW::SamplerData const*, unsigned int, unsigned int*) + 64
1 QuartzCore 0x01cda0fa CA::OGL::SW::sample_texture(CA::OGL::SW::Texture const*, int, unsigned int, CA::OGL::SW::Poly::Vertex const*, CA::OGL::SW::Poly::Vertex const*, CA::OGL::SW::Poly::Vertex const*, CA::OGL::SW::Poly::Vertex const*, unsigned char, unsigned int, unsigned int*) + 686
2 QuartzCore 0x01cdbc4b CA::OGL::SW::scanline(CA::OGL::SW::ScanState const*, int, int, int, CA::OGL::SW::Poly::Vertex*, CA::OGL::SW::Poly::Vertex const*, CA::OGL::SW::Poly::Vertex*, CA::OGL::SW::Poly::Vertex const*, unsigned int) + 1172
3 QuartzCore 0x01cdd3bd CA::OGL::SW::scan_convert_thread(void*, void*) + 3009
4 QuartzCore 0x01cff92f CA::DispatchGroup::dispatch(bool) + 191
5 QuartzCore 0x01cff969 CA::DispatchGroup::callback_1(void*) + 25
6 libdispatch.dylib 0x047944e6 _dispatch_worker_thread2 + 284
7 libsystem_c.dylib 0x9930db24 _pthread_wqthread + 346
8 libsystem_c.dylib 0x9930f6fe start_wqthread + 30
I had a similar problem that occurred on the simulator in 4.3 and 5.0. I was finally able to squash it by removing an unnecessary call to [self setNeedsDisplay] in the setFrame selector of a subclass of UIView that was set up to return a CATiledLayer in response to its class method +(Class)layerClass.
It's a problem in CATiledLayer where the call of the static method (Class)layerClass. and specifically in the initialization function where you set the size of the tileSize. make sure it's not 0;
Go to Xcode -> Preferences -> Downloads
Make sure your target SDK you have set in your project is installed in Xcode.

intermittent extaudiofileread exc_bad_access

I have what at the moment seems like an unsolvable EXC_BAD_ACCESS problem.
I've tried enabling NSZombie, as seems to be the advice in many posts but I'm dealing with c pointers and not obj c objects so I'm not getting any useful debugging information.
The way my code works is that in advance of it needing some audio from disk I detach a new posix thread passing it a pointer to information about the audio I want. Then I read some samples.
The reason I chose posix over NSThread or NSOperation is because it seemed to perform quicker. My audio is quite cpu intensive so I need to read audio as quick as possible.
How can I fix this bad access error? It doesnt occur all of the time. Sometimes it seems to happen when the application is very busy. Very occasionally it doesnt happen at all.
Is there anyway I could just throw a try catch around this as a quick fix? How else can I investigate causes of this is happening?
Edit This is a link to a seperate question I asked but it is related to the same problem
[Threading for intense io][1]
//detachnewthread gets called from remoteio callback
void detachnewthread(AudioSourceOBJ str)
{
//..... code removed for brevity
if(str)
{
int rc;
rc = pthread_create(&str->thread, NULL, FetchAudio, (void *)str);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
}
void *FetchAudio(void *threadid)
{
AudioSourceOBJ soundptr=threadid;
AudioUnitSampleType *outSamplesChannelLeft;
AudioUnitSampleType *outSamplesChannelRight;
outSamplesChannelLeft = (AudioUnitSampleType *) soundptr->queuebuffer->ABL->mBuffers[0].mData;
outSamplesChannelRight = (AudioUnitSampleType *)soundptr->queuebuffer->ABL->mBuffers[0].mData;
// ExtAudioFileRef audioFileRef;
// result= ExtAudioFileOpenURL(str->path, &str->audioFileObject);
AudioStreamBasicDescription importFormat = {0};
size_t bytesPerSample = sizeof (AudioUnitSampleType);
// Fill the application audio format struct's fields to define a linear PCM,
// stereo, noninterleaved stream at the hardware sample rate.
importFormat.mFormatID = kAudioFormatLinearPCM;
importFormat.mFormatFlags = kAudioFormatFlagsAudioUnitCanonical;
importFormat.mBytesPerPacket = bytesPerSample;
importFormat.mFramesPerPacket = 1;
importFormat.mBytesPerFrame = bytesPerSample;
importFormat.mChannelsPerFrame = 2; // 2 indicates stereo
importFormat.mBitsPerChannel = 8 * bytesPerSample;
importFormat.mSampleRate = 44100;
ExtAudioFileSetProperty (
engineDescribtion.audiofilerefs[soundptr->audioindex],
kExtAudioFileProperty_ClientDataFormat,
sizeof (importFormat),
&importFormat
);
UInt32 numberofframestoread=(soundptr->amounttoread);
AudioBufferList *bufferList;
bufferList = (AudioBufferList *) malloc (
sizeof (AudioBufferList) + sizeof (AudioBuffer) * (1)
);
// initialize the mNumberBuffers member
bufferList->mNumberBuffers = 2;
// initialize the mBuffers member to 0
AudioBuffer emptyBuffer = {0};
size_t arrayIndex;
for (arrayIndex = 0; arrayIndex < 2; arrayIndex++) {
bufferList->mBuffers[arrayIndex] = emptyBuffer;
}
// set up the AudioBuffer structs in the buffer list
bufferList->mBuffers[0].mNumberChannels = 1;
bufferList->mBuffers[0].mDataByteSize = numberofframestoread * sizeof (AudioUnitSampleType);
bufferList->mBuffers[0].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
bufferList->mBuffers[1].mNumberChannels = 1;
bufferList->mBuffers[1].mDataByteSize = numberofframestoread * sizeof (AudioUnitSampleType);
bufferList->mBuffers[1].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
AudioUnitSampleType *inSamplesChannelLeft=bufferList->mBuffers[0].mData;
AudioUnitSampleType *inSamplesChannelRight=bufferList->mBuffers[1].mData;
// UInt32 read=(UInt32)soundptr->fetchsample;
UInt32 read_plus_half_buffer=soundptr->fetchsample;
UInt32 readdestination= read_plus_half_buffer+numberofframestoread;
UInt32 actualsamplesread=0;
actualsamplesread=numberofframestoread;
if (readdestination>soundptr->perfectframecount) {
UInt32 readinpt1=0;
UInt32 readoutpt1=0;
UInt32 readinpt2=0;
UInt32 readoutpt2=0;
Float32 readtillendamount=0;
readinpt1=read_plus_half_buffer;
readoutpt1=soundptr->perfectframecount;
readinpt2=0;
if(read_plus_half_buffer>soundptr->perfectframecount)
{
readtillendamount=numberofframestoread;
readinpt1=read_plus_half_buffer-soundptr->perfectframecount;
}else
{
readtillendamount=soundptr->perfectframecount - readinpt1;
readoutpt2=numberofframestoread-readtillendamount;
}
actualsamplesread= readtillendamount;
ExtAudioFileSeek(engineDescribtion.audiofilerefs[soundptr->audioindex], readinpt1);
ExtAudioFileRead(engineDescribtion.audiofilerefs[soundptr->audioindex],&actualsamplesread , bufferList);
int writeposition=soundptr->queuebuffer->position;
for (int i=0; i<actualsamplesread; i++) {
outSamplesChannelLeft[writeposition]=inSamplesChannelLeft[i];
outSamplesChannelRight[writeposition]=inSamplesChannelRight[i];
writeposition++;
}
if (actualsamplesread!=readtillendamount) {
UInt32 newzeroamount= readtillendamount-actualsamplesread;
for (int j=0; j<newzeroamount; j++) {
outSamplesChannelLeft[writeposition]=0;
outSamplesChannelRight[writeposition]=0;
writeposition++;
}
}
bufferList->mBuffers[1].mDataByteSize = readoutpt2 * sizeof (AudioUnitSampleType);
bufferList->mBuffers[0].mDataByteSize = readoutpt2 * sizeof (AudioUnitSampleType);
ExtAudioFileSeek(engineDescribtion.audiofilerefs[soundptr->audioindex], 0);
ExtAudioFileRead(engineDescribtion.audiofilerefs[soundptr->audioindex],&readoutpt2 , bufferList);
for (int k=0; k<readoutpt2; k++) {
outSamplesChannelLeft[writeposition]=inSamplesChannelLeft[k];
outSamplesChannelRight[writeposition]=inSamplesChannelRight[k];
writeposition++;
}
}else if(readdestination<=soundptr->perfectframecount){
ExtAudioFileSeek(engineDescribtion.audiofilerefs[soundptr->audioindex], read_plus_half_buffer);
bufferList->mBuffers[1].mDataByteSize = actualsamplesread * sizeof (AudioUnitSampleType);
bufferList->mBuffers[0].mDataByteSize = actualsamplesread * sizeof (AudioUnitSampleType);
// crash happens here
if(bufferList)
{
assert( ExtAudioFileRead(engineDescribtion.audiofilerefs[soundptr->audioindex],&actualsamplesread , bufferList));
}else
{
printf("NO BUFFER");
}
int writeposition=soundptr->queuebuffer->position;
for (int i=0; i<actualsamplesread; i++) {
outSamplesChannelLeft[writeposition]=inSamplesChannelLeft[i];
outSamplesChannelRight[writeposition]=inSamplesChannelRight[i];
writeposition++;
}
if (actualsamplesread!=numberofframestoread) {
int zerosamples=0;
zerosamples=numberofframestoread-actualsamplesread;
for (int j=0; j<zerosamples; j++) {
outSamplesChannelLeft[writeposition]=0;
outSamplesChannelRight[writeposition]=0;
writeposition++;
}
}
}else
{
printf("unknown condition");
}
free(bufferList->mBuffers[0].mData);
free(bufferList->mBuffers[1].mData);
free(bufferList);
bufferList=nil;
soundptr->queuebuffer->isreading=NO;
// pthread_detach(soundptr->thread);
// free(&soundptr->m_lock);
return 0;
// pthread_exit(NULL);
}
Edit 2
O.K I've figured out how to use malloc history. I have a big trace statement. This is the first time I've ever seen anything like this before & I don't know how to use it to help myself.
ALLOC 0x6c67000-0x6c67fd7 [size=4056]: thread_a019c540 |start | main | UIApplicationMain | GSEventRun | GSEventRunModal | CFRunLoopRunInMode | CFRunLoopRunSpecific | __CFRunLoopRun | __CFRunLoopDoSource1 | __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ | migHelperRecievePortCallout | _XReceivedStatusBarDataAndActions | _UIStatusBarReceivedStatusBarDataAndActions | -[UIStatusBarServer _receivedStatusBarData:actions:] | -[UIStatusBarForegroundView setStatusBarData:actions:animated:] | -[UIStatusBarLayoutManager updateItemsWithData:actions:animated:] | -[UIStatusBarLayoutManager _updateItemView:withData:actions:animated:] | -[UIStatusBarItemView updateContentsAndWidth] | -[UIStatusBarTimeItemView contentsImageForStyle:] | -[UIStatusBarItemView drawText:forStyle:] | -[UIStatusBarItemView drawText:forStyle:forWidth:lineBreakMode:letterSpacing:] | -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:] | -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:includeEmoji:] | -[NSString(WebStringDrawing) _web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:] | -[NSString(WebStringDrawing) __web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:measureOnly:] | -[NSString(WebStringDrawing) __web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:measureOnly:renderedStringOut:] | drawAtPoint(unsigned short const*, int, WebCore::FloatPoint const&, WebCore::Font const&, WebCore::GraphicsContext*, WebCore::BidiStatus*, int) | WebCore::Font::drawSimpleText(WebCore::GraphicsContext*, WebCore::TextRun const&, WebCore::FloatPoint const&, int, int) const | WebCore::Font::drawGlyphBuffer(WebCore::GraphicsContext*, WebCore::GlyphBuffer const&, WebCore::TextRun const&, WebCore::FloatPoint&) const | WebCore::Font::drawGlyphs(WebCore::GraphicsContext*, WebCore::SimpleFontData const*, WebCore::GlyphBuffer const&, int, int, WebCore::FloatPoint const&, bool) const | WebCore::showGlyphsWithAdvances(WebCore::FontPlatformData const&, CGContext*, unsigned short const*, CGSize const*, unsigned long) | CGContextShowGlyphsWithAdvances | draw_glyphs | ripc_DrawGlyphs | ripc_RenderGlyphs | CGGlyphLockLockGlyphBitmaps | create_missing_bitmaps | CGFontCreateGlyphBitmap8 | aa_create | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fd7 [size=4056]: thread_a019c540 |start | main | UIApplicationMain | GSEventRun | GSEventRunModal | CFRunLoopRunInMode | CFRunLoopRunSpecific | __CFRunLoopRun | __CFRunLoopDoSource1 | __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ | migHelperRecievePortCallout | _XReceivedStatusBarDataAndActions | _UIStatusBarReceivedStatusBarDataAndActions | -[UIStatusBarServer _receivedStatusBarData:actions:] | -[UIStatusBarForegroundView setStatusBarData:actions:animated:] | -[UIStatusBarLayoutManager updateItemsWithData:actions:animated:] | -[UIStatusBarLayoutManager _updateItemView:withData:actions:animated:] | -[UIStatusBarItemView updateContentsAndWidth] | -[UIStatusBarTimeItemView contentsImageForStyle:] | -[UIStatusBarItemView drawText:forStyle:] | -[UIStatusBarItemView drawText:forStyle:forWidth:lineBreakMode:letterSpacing:] | -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:] | -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:includeEmoji:] | -[NSString(WebStringDrawing) _web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:] | -[NSString(WebStringDrawing) __web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:measureOnly:] | -[NSString(WebStringDrawing) __web_drawAtPoint:forWidth:withFont:ellipsis:letterSpacing:includeEmoji:measureOnly:renderedStringOut:] | drawAtPoint(unsigned short const*, int, WebCore::FloatPoint const&, WebCore::Font const&, WebCore::GraphicsContext*, WebCore::BidiStatus*, int) | WebCore::Font::drawSimpleText(WebCore::GraphicsContext*, WebCore::TextRun const&, WebCore::FloatPoint const&, int, int) const | WebCore::Font::drawGlyphBuffer(WebCore::GraphicsContext*, WebCore::GlyphBuffer const&, WebCore::TextRun const&, WebCore::FloatPoint&) const | WebCore::Font::drawGlyphs(WebCore::GraphicsContext*, WebCore::SimpleFontData const*, WebCore::GlyphBuffer const&, int, int, WebCore::FloatPoint const&, bool) const | WebCore::showGlyphsWithAdvances(WebCore::FontPlatformData const&, CGContext*, unsigned short const*, CGSize const*, unsigned long) | CGContextShowGlyphsWithAdvances | draw_glyphs | ripc_DrawGlyphs | ripc_RenderGlyphs | CGGlyphLockLockGlyphBitmaps | create_missing_bitmaps | CGFontCreateGlyphBitmap8 | aa_destroy | free
ALLOC 0x6c67000-0x6c67fff [size=4096]: thread_b024f000 |thread_start | _pthread_start | __NSThread__main__ | -[NSThread main] | -[FirstViewController checkstate:] | CALayer_setter_kCAValueFloat | CALayer_setter | CA::Transaction::ensure_compat() | CA::Transaction::create() | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fff [size=4096]: thread_b024f000 |thread_start | _pthread_start | __NSThread__main__ | -[NSString compare:options:] | _pthread_exit | _pthread_tsd_cleanup | free
ALLOC 0x6c67000-0x6c67fff [size=4096]: thread_b0353000 |thread_start | _pthread_start | __NSThread__main__ | -[NSThread main] | -[FirstViewController checkstate:] | CALayer_setter_kCAValueFloat | CALayer_setter | CA::Transaction::ensure_compat() | CA::Transaction::create() | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fff [size=4096]: thread_b0353000 |thread_start | _pthread_start | __NSThread__main__ | -[NSString compare:options:] | _pthread_exit | _pthread_tsd_cleanup | free
ALLOC 0x6c67000-0x6c67fff [size=4096]: thread_b0763000 |thread_start | _pthread_start | FetchAudio | ExtAudioFileRead | ExtAudioFile::Read(unsigned long, unsigned long&, AudioBufferList*) | AudioConverterFillComplexBuffer | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | AudioConverterChain::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | CBRConverter::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::GetInputBytes(unsigned long, unsigned long&, CABufferList const*&) | CABufferList::AllocateBuffers(unsigned long) | operator new[](unsigned long) | operator new(unsigned long) | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fff [size=4096]: thread_b0763000 |thread_start | _pthread_start | FetchAudio | ExtAudioFileRead | ExtAudioFile::Read(unsigned long, unsigned long&, AudioBufferList*) | AudioConverterFillComplexBuffer | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | AudioConverterChain::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | CBRConverter::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::GetInputBytes(unsigned long, unsigned long&, CABufferList const*&) | free
ALLOC 0x6c67000-0x6c67fff [size=4096]: thread_b0a6f000 |thread_start | _pthread_start | FetchAudio | ExtAudioFileRead | ExtAudioFile::Read(unsigned long, unsigned long&, AudioBufferList*) | AudioConverterFillComplexBuffer | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | AudioConverterChain::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | CBRConverter::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::GetInputBytes(unsigned long, unsigned long&, CABufferList const*&) | CABufferList::AllocateBuffers(unsigned long) | operator new[](unsigned long) | operator new(unsigned long) | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fff [size=4096]: thread_b0a6f000 |thread_start | _pthread_start | FetchAudio | ExtAudioFileRead | ExtAudioFile::Read(unsigned long, unsigned long&, AudioBufferList*) | AudioConverterFillComplexBuffer | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | AudioConverterChain::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::FillBuffer(unsigned long&, AudioBufferList&, AudioStreamPacketDescription*) | CBRConverter::RenderOutput(CABufferList*, unsigned long, unsigned long&, AudioStreamPacketDescription*) | BufferedAudioConverter::GetInputBytes(unsigned long, unsigned long&, CABufferList const*&) | free
ALLOC 0x6c67000-0x6c67fff [size=4096]: thread_b0081000 |thread_start | _pthread_start | __NSThread__main__ | -[NSThread main] | -[FirstViewController checkstate:] | CALayer_setter_kCAValueFloat | CALayer_setter | CA::Transaction::ensure_compat() | CA::Transaction::create() | malloc | malloc_zone_malloc
----
FREE 0x6c67000-0x6c67fff [size=4096]: thread_b0081000 |thread_start | _pthread_start | __NSThread__main__ | -[NSString compare:options:] | _pthread_exit | _pthread_tsd_cleanup | free
I notice the following lines in your code:
bufferList = (AudioBufferList *) malloc (
sizeof (AudioBufferList) + sizeof (AudioBuffer) * (1)
);
// initialize the mNumberBuffers member
bufferList->mNumberBuffers = 2;
You are malloc'ing an AudioBufferList to have the capacity of one AudioBuffer, but then indicating that it actually has two. Try changing that "* (1)" to "* (2)".
In addition to this, you shouldn't perform malloc's or ExtAudioFileOpen's in the thread, as those will take up time. If you can manage to pre-perform the malloc's and ExtAudioFileOpen's and just keep them in a struct array for your files, you may find a increase in performance / stability.
I may not have read the code completely properly as it looks like the formatting got a little messed up, but I hope this helps.
You fix this by locating it and figuring out why it is wrong, not by a try/catch.
Guard Malloc can help you identify many issues in your program. It is a diagnostic option which you can enable in Xcode. The intent of the option is to fail when you attempt to read or write memory you do not own, making it clearer than usual which part of your program is causing issues. full details: man guardmalloc. The first step is to correct all issues guardmalloc points out. You should be able to run your app for hours without these issues.
If you want exceptions and runtime checks to help you identify these issues earlier on (which is worth your consideration), consider C++ rather than C for your implementations.
Update
if it's a heap allocation that is the allocation in question, then malloc logging will likely help you. when malloc logging is enabled and the debugger pauses execution, just use malloc_history to view the callstack for the allocation. malloc_history will lookup the address in the log and dump the callstack of the alloc's creation. from there, you just follow the allocation's flow through your program to find what you are getting wrong.
I eventually found the solution to this problem. Every time I needed audio I created a new thread to fetch the audio. On occassion while a thread was fetching audio for a particular the buffer the same buffer would request data again resulting in the same buffer be accessed at the same time, thus the exc_bad_access.
I solved this by having just one thread waiting and being signalled to get data using posix condition.
All of the answers here were useful and have helped me learn a lot about debugging. Thanks guys..
The problem is almost certainly happening because your reading memory that you shouldn't be. Hence the EXC_BAD_ACCESS. What's essential is that the sizes of your buffers, and the amount of memory that you are reading is all correct. For example if you try to read more than a buffer's worth, you'll receive an error.
In ExtAudioFileRead, the value at &readoutpt2 should specify the number of frames. Are you sure this value is correct? Is bufferList big enough to store that number of frames? Are you advancing a pointer through bufferList as you read data, and is the amount you advance correct?
Are you correctly allocating memory based upon the underlying type? For example is your audio data integer or floating point format?
Basically, everything needs to add up correctly otherwise you will blow a buffer somewhere!
One other tool to try for tracking down memory issues is guard malloc. You can find more info here Enabling the Malloc Debugging Features

Memory leak dyld dlopen

I am getting leak and I cannot detect from where this is happening. The stack trace does not give full info after dyld open. For few leaks I am not getting any stack trace info. All I get is only object memory address. Is anyone else facing the same issue. I am using XCode 3.2 on show leopard.
18 0x103038
17 0x1033c7
16 0x1034a1
15 0x90145f48
14 dyld dlopen
13 dyld dyld::link(ImageLoader*, bool, ImageLoader::RPathChain const&)
12 dyld ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, ImageLoader::RPathChain const&)
11 dyld ImageLoader::recursiveLoadLibraries(ImageLoader::LinkContext const&, bool, ImageLoader::RPathChain const&)
10 dyld dyld::libraryLocator(char const*, bool, char const*, ImageLoader::RPathChain const*)
9 dyld dyld::load(char const*, dyld::LoadContext const&)
8 dyld dyld::loadPhase0(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*)
7 dyld dyld::loadPhase1(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*)
6 dyld dyld::loadPhase3(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*)
5 dyld dyld::loadPhase4(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*)
4 dyld dyld::loadPhase5(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*)
3 dyld dyld::mkstringf(char const*, ...)
2 dyld strdup
1 dyld mallocenter
I'm seeing very similar behavior in xcode 3.2. The dyld leak, that didn't appear in xcode 3.1.x, and I'm not seeing anything other than a memory address for any other leaks. Just to prove I wasn't crazy, I instantiated several UILabels using alloc and didn't release them. Sure enough, xcode shows UILabel leaks, but the stacktrace is only memory addresses. In 3.1.x I used to see a stack that was much more meaningful, complete with class names. Is this a bug in the new xcode?