C best practices, stack vs heap allocation

2019-01-20 01:40发布

问题:

I have been using c a lot more recently and finding that I really don't like dealing with memory management, or at least the idea that if I malloc a pointer I have to release it even if its the most trivial thing. This has lead me to allocating as much as possible on the stack and using & to get its location. Even making separate int and inptr variables(I've had some lvalue problem with & operator in macros).

I haven't find many places where I have had to deal with passing data up (above/below) where it was allocated. At the same time I need a decent amount of early returns(and I would rather avoid gotos). What is the general c opinion say? Are there any obvious signs I should use one or another in a particular case.

P.S. One thing that made me worry a bit was that I recently got a memory corruption problem due to using the wrong sizeof for malloc and I didn't notice it right away since most of my code paths directly after that point didn't utilise the heap. How big of a problem do you think this sort of corruption hiding might be?

回答1:

You should use malloc if:

  1. You're passing pointers to non-static const data up the call stack, or
  2. you're allocating variable or simply large amounts of data (else you risk stack overflow).

In other cases, stack allocation should be fine.



回答2:

A bit tongue cheek: the surest sign is when you run out of stack.

One additional situation besides what larmans mentioned is when you want return data to the caller, in most cases when the returned data is complex its more effective to return a pointer than return a copy.



回答3:

While technically not directly related to the OP's question, it's in the same ball-park (which I figure is sufficient justification for my answer).

You might want to take a look at the "Boehm C Garbage Collector". It's a time tested piece of software and I've used it many times without any problems. This lets you effectively use malloc for everything and just forget about the corresponding free.



回答4:

Stack allocation is useful when you have to deal with a small amount of data and this data is needed only in one function. If you have to pass pointers between functions instead, you better malloc() the memory on the heap due to the fact that once you exit from a function its stack could be overwritten at every time. Having more than 127 bytes of local data will slow down the execution since if the offset is within this limit it can be included in the instruction itself (e.g. mov eax, [ebp - 4]), so character buffers should be allocated on the heap (if you aren't sure they won't exceed this limit). One more thing about free() (at cost being downvoted ;): freeing your memory isn't required, if fact the os will claim back all the memory it gave to you application, but it's bad programming practice, sign of laziness and may cause memory leaks or any kind of errors.