Reputation: 165
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)
Upvotes: 1
Views: 210
Reputation: 7345
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.
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?
Upvotes: 3
Reputation: 47923
As a counterpoint to the accepted answer:
While it is indeed good advice to avoid using malloc
when you don't need it, it is important to know how to use it properly when you do need it — because there are plenty of times when you do need it! In fact I would go so far as to say that just about any program that does something interesting with data, will want to dynamically allocate memory for that data.
For example, if you're writing a text editor, you're not going to want to limit your users to some fixed maximum number of lines of text that you statically allocated when you write the text editor — you're going to want to allocate data structures for as many lines of text as your user is editing on any given day. Maybe just a few, or maybe a huge number.
It's true that there are many bugs that can crop up when malloc
is used improperly. But there are also plenty of coding patterns that allow malloc
to be used safely and conveniently. Those patterns are worth learning and using!
Upvotes: 5