Feb 05

I was seeing this error message when testing an app on a device:

Mashable(1870,0x3940f7e0) malloc: *** mmap(size=3802099712) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

Trying to allocate 3.8 GB of memory on an iPhone isn’t likely to succeed, although the simulator is all to happy to comply.

After some debugging I found this code:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger numRows;
	
    NSArray *headlines = [[BlogService sharedInstance] headlines];
    if (headlines) {
        numRows = [headlines count];
    }
	
    return numRows;
}

Ouch! Returning a variable that has not been initialized and is therefore pointing to a random location in memory is not going to lead to anything good.

Moral of the story: Always initialize your variables. Test early and often on a device.

written by Nick \\ tags:

4 Responses to “Sloppy Coding”

  1. Trevor Says:

    This appears to be a language deficiency. The Objective-C compiler should not allow such code to exist. Other languages, such as Java, ensure definite assignment, and their compilers would flag the above code as illegal, preventing the problem before it starts.

  2. Nick Says:

    After 10 years in the coddled world of Java, Obj-C is sometimes a harsh awakening. 🙂

  3. toohtik Says:

    Also you can start static-analyze of your code, to find uninitialized variables in all project.

  4. Nick Says:

    @toohtik: Great advice! Today with the Clang Static Analyzer built-in to Xcode there is no excuse for not analyzing all your code on a continuous basis.

Leave a Reply