path / FastImageCache

iOS library for quickly displaying images while scrolling
MIT License
8.11k stars 935 forks source link

EXC_BAD_ACCESS #161

Open Montana opened 2 years ago

Montana commented 2 years ago

Hey ex Pathies,

When working on the product I remember anything you get from an allocation function (usually the static alloc method, but there are a few others), or a copy method, you own the memory too and must release it when you are done.

But say, if you get something back from just about anything else including factory methods (e.g. [NSString stringWithFormat]) then you'll have an autorelease reference, which means it could be released at some time in the future by other code - so it is vital that if you need to keep it around beyond the immediate function that you retain it. If you don't, the memory may remain allocated while you are using it, or be released but coincidentally still valid, during your emulator testing, but is more likely to be released and show up as bad access errors when running on the device.

Is the best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option on?

Spineswitch commented 2 years ago

Is the best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option on?

probably, or use something that can re-engineer getting malloc

Montana commented 2 years ago

I don't know about totally avoiding malloc, but I could certainly reduce it in this scenario.

The basic concept is a memory pool. That is a large buffer which you have allocated that you can use for many objects instead of requesting lots of small allocations.

You might use this in a real-world situation where you are sending events into a queue to be processed by another thread. The event objects might be smallish structures and you really need to avoid making thousands of calls to malloc every second.

In this scenario I can see myself already getting antsy, I'm picky about formatting and have to follow this style-guide I've been doing for years now:

int ** matrix = malloc( rows * sizeof(int*) );
matrix[0] = malloc( rows * cols * sizeof(int) );
for( int i = 1; i < rows; i++ ) {
    matrix[i] = matrix[i-1] + cols;
}

I digress though, so to your answer I cannot agree, but thanks for the input.