There is a problem with dynamic memory allocation, for example malloc or calloc of an array, when it is done in viewDidLoad. I had the same problem when replacing malloc with NSMutableData as suggested here. I do not need a solution, as I am going to propose my own, but would welcome discussion that would lead to a deeper understanding of iOS memory management. My code had the following sections:
In the class extension I defined the pointer
@interface MyFirstViewController () {
float* arrayPtr;
}
In viewDidLoad I allocated memory for the array, using malloc or calloc:
arrayPtr = malloc(100 * sizeof(float));
NSAssert(arrayPtr != NULL, @"Could not allocate memory for an array.");
The pointer would then be passed to another objective-c class, which would fill the array with data. The app would crash whenever it wanted. Losing access to the array at different indices (all within the proper range of indices). It seem to behave as if the array was deallocated.
My solution: Only set the pointer to NULL in viewDidLoad
arrayPtr = NULL;
In the method that you need the array, allocate it only the first time
if (arrayPtr == NULL) {
arrayPtr = calloc(100, sizeof(float)); // malloc is also working
NSAssert(arrayPtr != NULL, @"Could not allocate memory for an array");
}
// use the pointer (array) here. Pass it to the other class as needed...