[Swan-dev] heap allocation vs stack allocation

D. Hugh Redelmeier hugh at mimosa.com
Thu Apr 24 23:45:07 EEST 2014

I noticed that ikev2_out_nat_v2n allocated heap space for each hash.  
memory should be allocated on the stack as local variables.

Stack allocation is much better than heap allocation, if it is

- it is faster

- it does not contribute to heap fragmentation (dangerous and
  insidious in a long-running daemon)

- the system takes care of the lifecycle (including freeing)

- pointers are not required

- the lifetime is trivially evident to any programmer.

When is it appropriate?  Both these must be true:

- the stack lifetime is reasonable (sufficient and not excessive)

- the size is known at compile time or a reasonable bound on the
  size is known at compile time

In the case of ikev2_out_nat_v2n, the hash buffers would be much better 
stack-allocated than heap-allocated.

How many other places in the code have we used unnecessarily used heap

PS: in the code, the lifetime of the two hashes did not overlap, so
only one buffer is required.

More information about the Swan-dev mailing list