Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free and Malloc in a Loop - Correct Way to Free Memory?

I have the below loop (code simplified) :

for (int y = 0; y < 20; y++) {

self.array[y].numbers = [self getNumberData:source objectPass:object];

}

This calls the get NumberData method. In this code a malloc method is used, e.g :

object->item1 = malloc(sizeof(Class) * object->item2);

My question is how do I correctly free up the malloced memory ?

The self.array[y].numbers is a C struct.

Can I just put free (array) in the dealloc method ?

Thank you.

like image 307
GuybrushThreepwood Avatar asked Nov 27 '25 15:11

GuybrushThreepwood


1 Answers

You must pass the pointer returned by malloc to free.

So, if you've malloced up the whole array of structs in one swell foop, you can (and must) free the whole thing, as well.

If you've malloced each struct individually, you must free each, as well.

like image 188
Greg Jandl Avatar answered Nov 29 '25 06:11

Greg Jandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!