Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading