Tuesday, June 5, 2012

iOS: Stack Size Limit

In the iOS, there is currently a limit of 1MB stack size on the main thread and 512KB stack size on a secondary thread.

The most significant thing about this limit is that primitive arrays are put on the stack if they are declared like this:
char carr[size];
int iarr[size];

If you have more than 512KB of them at a time on a secondary thread, you will get an error.

The solution is to allocate arrays on the heap using malloc e.g.:
char *byteBuffer = malloc(1000000);

You'll have to call "free(byteBuffer)" after you're done with it to release the allocated memory. Note that if you're using ARC, ARC does not do it for you. If it's an instance variable, you'll have to override the dealloc method of the object that owns the array, and free it in the dealloc method.

If it's an array that won't change very much, it's usually OK to just use NSData or NSMutableData. However if it's an array that will change very much, then you have to use malloc.

References

No comments:

Post a Comment