iosmemory-managementinstrumentscgpdfdocument

CGContextDrawPDFPage crashing without ever producing a memory warning


I'm trying to render a PDF page with some annotations on it (to email), and most of the time this works fine.

However, with this PDF in particular it seems to crash every time on the call to CGContextDrawPDFPage for the first page. I have added

CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);

as a recommendation from CGContextDrawPDFPage taking up large amounts of memory but that did not seem to solve my issue.

I ran this through the profiler to see what was going on, and it slowly started allocating a bunch of memory until finally it hit 512MB of live bytes and died. memory allocation profiled in instrument

The strange thing is that when I render this to an image (for display on the device) context it seems to work fine but when I render it to a PDF context (for emailing with annotations), it breaks. All of the other PDFs I've tried work fine in both cases.

I was hoping that someone who's written a PDF viewer/annotator could test this out and see if this document works for them and if so, give me some tips about what they're doing to reduce the memory allocations of CGContextDrawPDFPage.

Another resource I looked at was this great SO Question.

Edit (more info on the crash):

90% of the time the crash doesn't actually show up, the gdb line displays but the app goes away and the stack trace doesn't show. (It says paused but there is no thread display). One time I saw it was an exc_bad_access and it showed this in the log:

malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

Solution

  • Are you constructing the PDF on the main thread? If so, you may not receive the memory warning because you've blocked the signal while in execution, since the run loop never has a chance to dispatch the message to you.