Home > database >  Why do I always hear to avoid allocating memory when I can in C?
Why do I always hear to avoid allocating memory when I can in C?

Time:02-05

I am always told to not allocate memory whenever I can achieve the exact same thing without it.
Do people say that because freeing things in your code can take some time, or is there an efficiency-oriented explanation? (e. g. better performance)

CodePudding user response:

Because managing memory is complicated and prone to all kinds of bugs. It's too easy to forget to free() something, or free() something twice, or use something after free()ing it. Allocating memory from the heap is also more expensive, and has some fair amount of overhead.

I am always told to not allocate memory whenever I can achieve the exact same thing without it.

And that's good advice. Forego dynamic memory allocation when you can do without it. You should only be allocating memory from the heap when the size of the allocation is not known at compile time, such as user input. But even then you should specify an upper bound, and if the input exceeds that limit, deny service to the user.

See also: Why is memory allocation on heap MUCH slower than on stack? and Malloc or normal array definition? and When do I need dynamic memory?

  • Related