Reputation: 30078
What is the Best practice to allocate memory for primitive types in objective-c?
Is using C allocations is okey (malloc and free)
unsigned int* val = malloc(sizeof(unsigned int));
free(val);
Or Is there any obj-c specific allocations?
And Which is better if a function expects an pointer to int, creating and managing the pointer myself, or just create a regular variable and send its address using the address-of
operator:
The first form:
NSScanner* scanner = [NSScanner scannerWithString: @"F"];
unsigned int* val = malloc(sizeof(unsigned int));
[scanner scanHexInt: val];
NSLog(@"%d", *val);
free(val);
The second form:
NSScanner* scanner = [NSScanner scannerWithString: @"F"];
unsigned int val;
[scanner scanHexInt: &val];
NSLog(@"%d", val);
Myself with the second form to free myself from the alloc-free memory headache.
Upvotes: 1
Views: 409
Reputation: 244
Both forms are valid and have pros/cons, but the first one is extra work in this example and has negative performance implications as compared to the second form.
In the first form, you will be allocating that int on the heap, so malloc's subsystem will have to perform bookkeeping to make sure there is an allocation available. You will also have to remember to free the allocation at the correct time.
In the second form, the allocation will be made on the stack, which has much less bookkeeping required than malloc does. It will also automatically be free for you when you leave this function.
The key time to use malloc/free is if you want the scope of your variable to last outside of the current function. Otherwise, when you leave the function the stack will be popped and you will lose the data.
Upvotes: 3