Hrishikesh_Pardeshi
Hrishikesh_Pardeshi

Reputation: 995

Memory allocation fails in the background in the ios app

I am trying to create a few 2-D array of unsigned integers in a function which is to used locally. However, the app crashes when it moves to the background. I tried out the following code after that:

For the background task:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){
        if([[UIDevice currentDevice] isMultitaskingSupported]){
            __block UIBackgroundTaskIdentifier bgTask;
            UIApplication *application = [UIApplication sharedApplication];
            bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
                [application endBackgroundTask:bgTask];
                bgTask = UIBackgroundTaskInvalid;
            }];

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //[self captureImage];
                [self memCheck];
                [application endBackgroundTask:bgTask];
                bgTask = UIBackgroundTaskInvalid;
            });
        }
    }
}

The function:

-(void) memCheck{
    size_t XY[768][1024];
    for(int i=0;i<768; ++i){
        for(int j=0;j<1024;++j){
            XY[i][j]=1;
        }
    }      
}

The above test code snippet causes the app to crash. But, if I try to allocate just 768*4 bytes rather than 768*1024*4, it works fine.

Is it that the OS suspends the app due to memory bloat or any other reason ? Also, is there a workaround for this ?

Thanks.

P.S: I have used IOSurfaces (part of the private iOS API), created and released them in the background and I never encountered this issue.

Upvotes: 0

Views: 291

Answers (1)

Matthias
Matthias

Reputation: 8180

Probably, this is not a background problem but a general threading issue. By using dispatch_async you execute the block within a secondary thread. Apple's documentation suggests that the stack size is 512 KB. Local variables are usually allocated a the stack. Thus, an array of 768*1024*4 =3.145.728 exceeds the stack limit.

Upvotes: 1

Related Questions