4 ms·
> Do not use fixed size buffers with variable sized data - always calculate how much space you’ll need and allocate it. Actually, sometimes it is best to have
by kahlonel 7y ago
> Do not use fixed size buffers with variable sized data - always calculate how much space you’ll need and allocate it.
Actually, sometimes it is best to have a fixed size buffer, sized appropriately for the maximum data-bytes allowed as per design. Especially true for embedded systems where dynamic allocation is usually frowned upon.
- ddevault 7y agoAuthor here. In the 2 years (almost 3 now) since this was written, I've come around on this argument. I often use fixed size buffers when I know how much space I'll need in advance, of course being careful to measure twice, cut once.
- rlonn 7y agoI use fixed-size buffers as much as possible in C. It's only when I feel a need to conserve memory that I'll use dynamic allocation. For me, I think this pattern helps me avoid bugs by maintaining a healthy (i.e. very high) level of paranoia when dealing with buffers. My first thought when doing something involving a buffer is always "how much space have I allocated here?". With string buffers I'll never use the last byte of the buffer - that one is permanently set to zero and never read or written to. I'll commonly zero the whole buffer before writing to it also. That way any operation not doing proper null-termination will not matter.
- ncmncm 7y agoIf there is one thing decades of experience has taught us about C, it is that the language is not naturally well-suited to safe and reliable buffer management. This means that if you are coding C and using buffers, good code will necessarily look and feel unnatural. You should be deeply suspicious of any code you find managing buffer contents that has nothing awkward-looking. Managing buffers correctly in C takes far above average care and attention. That care needs to leave tracks to show it happened, and to remind subsequent maintainers to exercise it too.