5 ms·
Or even better: for local small allocations just use the stack.
by faragon 10y ago
Or even better: for local small allocations just use the stack.
- vertex-four 10y agoAlloca is non-standard and apparently a C11 compliant compiler can choose not to implement variable-length arrays - there's no standard way of allocating on the stack. Also - are you utterly certain your allocations will always be small? Could someone craft some input to your program to have you allocate more, and possibly use up the stack in some environments? There's environments which have much smaller stacks than have RAM available.
- faragon 10y agoYou can do stack allocation in C without "alloca()", e.g. size_t example(const char in, const size_t in_size, char out, const size_t max_out_size) { size_t out_size = 0; char stack_buf[32768]; char *buf = stack_buf; char *heap_buf = NULL; size_t req_size = in_size * 2; if (req_size < sizeof(stack_buf)) { buf = heap_buf = (char *)malloc(req_size); } // Do stuff if (heap_buf) { free(heap_buf); } return out_size; }
- vertex-four 10y agoThat's precisely what's being done in curl. Generally when people say "stack allocation" as an alternative to "malloc" they mean alloca/VLA, so you'll forgive my confusion.
- faragon 10y agoERRATA: if (req_size < sizeof(stack_buf)) Should be: if (req_size > sizeof(stack_buf))
- maccard 10y agoYou don't always know up front how much space you need.
- faragon 10y agoYou can guess a maximum for covering 99.99% of the cases, and use dynamic memory just in the 0.01%. E.g. size_t example(const char in, const size_t in_size, char out, const size_t max_out_size) { size_t out_size = 0; char stack_buf[32768]; char *buf = stack_buf; char *heap_buf = NULL; size_t req_size = in_size * 2; if (req_size < sizeof(stack_buf)) { buf = heap_buf = (char *)malloc(req_size); } // Do stuff if (heap_buf) { free(heap_buf); } return out_size; }
- faragon 10y agoERRATA: if (req_size < sizeof(stack_buf)) Should be: if (req_size > sizeof(stack_buf))