It depends on what you need the buffer for.
Do you really need to clear it after every iterations or maybe a \0
char at the end would suffice to mark the end of a string? After all that's what the various str
library calls use.
If you really need to clear it you can use bzero()
. Certainly malloc'ing and free'ing at every iteration is a waste of resources, since you can happily re-use the buffer.
A different problem would arise if you were to parallelize the for loop, i.e. to have several concurrent threads using it.
Simple, real-life example: using a bucket to carry water. Suppose you need to do several trip with that bucket: would it make sense to pick it up, use it, put it down, pick it up again, use it, etc...? You can re-use the bucket as many times as possible.
If, on the other hand, the bucket needs to be used by you and more people, either you organize access to the bucket or need more buckets.
Last suggestion: do not worry about performances now. They say that early optimization is the root of all evil, and you'll soon understand why.
Firstly, understand the problem: write code that can be thrown away. Experiment.
Secondly, test it. Make sure it does what you need.
Thirdly, optimize it. Make the loop run ten thousand times and measure how long it takes. Then move the malloc outside, and measure again (use the shell command time
if under UNIX).
Fourthly, rewrite it because your first experiment will most likely be a mess of patches of try-retry-not working code.
Rinse, repeat.
ps: have fun in the mean time. It's supposed to be interesting, not frustrating.