54 ms·
its not all go specific, despite the comment about 'C style' heap allocation and pointer usage, you will find your C code will get better if you do not do this
by jheriko 11y ago
its not all go specific, despite the comment about 'C style' heap allocation and pointer usage, you will find your C code will get better if you do not do this as well. the heap is a last resort, not the first.
- scott_s 11y agoI found that comment strange as well - I consider "put everything on the heap" to be more of the default attitude in dynamic languages (Python, Ruby) and in the statically typed managed languages (Java, C#). In C and C++, I default to the stack, and I don't think I'm alone.
- adrusi 11y agoYeah, that was odd, I wonder if it was some kind of elaborate typo. Heap allocation is much worse in C than in Go because you're responsible for freeing everything you heap allocate. There are only a few good reasons to heap allocate in C: You're writing a library and want to be able to add fields to your data structures without breaking ABI compatibility. You need to return dynamically sized chunk of data, whose length can't be known to the caller ahead of time, like a string. Still consider returning it by writing to a statically sized buffer passed as an argument, piecewise, as in read(). You need a growable buffer. Still consider allocating a reasonable maximum sized buffer and BOUNDS CHECKING. Some library requires you to dynamically allocate to use its API. Oh well. You want to maintain API consistency and that requires dynamically allocating something that doesn't strictly need to be. Don't be dogmatic, but stack allocation, and occaisionally static allocation are much more maintainable than dynamic allocation.