1

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...
Community
  • 1
  • 1
Rahav
  • 1,755
  • 15
  • 18
  • This question appears to be off-topic because it is asking for a discussion, not an answer to a question. – borrrden Oct 03 '14 at 09:00
  • Please refer to this page -> http://stackoverflow.com/help/dont-ask – borrrden Oct 03 '14 at 09:00
  • The main reason I posted was because I offered a solution to a problem that I could not find an answer to on this (or any other) site. I saw a number of related questions by others, probably because people ask questions in different ways, but no solutions, so I also believe that this topic could benefit from some discussion. – Rahav Oct 04 '14 at 12:20

0 Answers0