开发者

malloc()'s "perfect efficiency" VS automatic variables

I had the habit for a while to call malloc on anything. Then it dawned to me if there's no performance critical section of the code, why not use a couple of kilobytes more on an automatic and lose the accuracy of the amount of memory I need (potentially) of the malloc procedure? That way with no noticeable impact one can make much more readable code. e.g. copying temporarily a string for manipulating it in开发者_Go百科 a function that is called very rarely.

Is my logic sound?


Local variables are stored on the stack, which is limited. malloc() allocates memory from the heap, which is also limited but contains far more memory.

I generally do not use malloc() unless the amount of memory would exceed what I could safely store on the stack.

For Windows development, the stacks are normally pretty large. You could store a buffer of up to a couple of hundred bytes without too much trouble (assuming the function would never be called recursively).

But, generally, if I need more than, say, 50 bytes, I would normally use malloc().


Most implementation's version of malloc() actually do not allocate the exact amount you specify but actually allocates more, usually in block-size increments. This gives a performance boost if you need to do some minor reallocation. So there was never really any "accuracy" there to begin with


I assume that you want to replace code like this:

malloc((foo * 2 + 6) * sizeof(char))

With

char big_enough[2000];

Regarding waste - there's nothing wrong with wasting a couple of bytes now and again, but if you do it all the time it will start to add up.

But a more serious danger is that you need to be sure that it's always going to be enough. Using a constant is dangerous - it might seem like 2000 bytes ought to be enough but are you sure that it's impossible for someone to need more? Remember that this sort of code can easily create buffer overflow vulnerabilities and the work you've saved in not calculating the correct size is probably less than the amount of extra work you now need to do to check that you don't overflow the buffer each time you read or write to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜