In programming there is a general rule introduced by Kernighan & Ritchie saying that you have call a “free” for all space allocated by a “malloc”.
So the following code is correct:
- (UIImage*) convertImage:(UIImage*)sourceImage {
unsigned char *rawData = malloc(requiredSpace);
...
...
free(rawData);
return imageRef;
}
However you also have encapsulation within a function. So after the return from the function, the memory will be automatically freed. So theoretically the free is not absolutely required in the above example. Is this correct?
Absolutely no.
The
freeis necessary since the memory will be freed only for statically allocated variables. If you usemalloc(as well ascallocorrealloc) you are dynamically allocating memory that will not be freed except if you explicitly callfree.For example:
awill be destroyed at the end of the scope (at least, will be marked as free memory, so that you cannot rely anymore on its content), whilebremains in memory until the end of the program. If you lose the pointer to that memory address (maybe assigning another value tobor simply ending the function without returningb), you will not be able to free the memory anymore, and this will bring to a memory leak.