Vincent
Vincent

Reputation: 4409

Free vs. encapsulation

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?

Upvotes: 0

Views: 85

Answers (1)

Manlio
Manlio

Reputation: 10864

Absolutely no.

The free is necessary since the memory will be freed only for statically allocated variables. If you use malloc (as well as calloc or realloc) you are dynamically allocating memory that will not be freed except if you explicitly call free.

For example:

-(void)method {

    char a[10];
    char *b = (char*) malloc(10*sizeof(char));

}

a will 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), while b remains in memory until the end of the program. If you lose the pointer to that memory address (maybe assigning another value to b or simply ending the function without returning b), you will not be able to free the memory anymore, and this will bring to a memory leak.

Upvotes: 4

Related Questions