return type of malloc

0
241

You can get a malloc-t, but you can’t get a return type. This is because malloc stores the memory on the stack so that the function can grow and shrink without having to explicitly write it out again. But if you’re going to be storing large amounts of memory, you obviously can’t leave it on the stack.

A lot of people would argue that this is a good thing, since it means that your stack will be smaller and more cache-friendly. But that can also make it prone to problems, so the debate goes on.

The argument against this is that a return type is what a function returns, not the memory on the stack. So if you want to store large amounts of memory, then you need to explicitly write it out again. A lot of people would say this is a bad thing, because you cant allocate huge amounts of memory on the stack then just keep it on the stack. But they’re wrong.

This is good news if you want to use malloc on the heap. You can now do this safely. You just need to remember to free() it when you’re done with it.

The problem is that, because the stack is a variable-sized collection of locations, it must be allocated on the heap. This can often lead to memory leaks as malloc gets confused by the stack and uses it for things that aren’t even on the stack such as temporary variables.

Avatar photo
I am the type of person who will organize my entire home (including closets) based on what I need for vacation. Making sure that all vital supplies are in one place, even if it means putting them into a carry-on and checking out early from work so as not to miss any flights!

LEAVE A REPLY

Please enter your comment!
Please enter your name here