4 ms·
VLAs are actually not so nice. There is no sane way to handle failures if you make one too big.
by sigjuice 10y ago
VLAs are actually not so nice. There is no sane way to handle failures if you make one too big.
- slrz 10y agoThen don't make it too big and fall back to malloc(3) above a certain threshold?
- sigjuice 10y agoDo you mind spelling out the few lines of code needed to do this?
- slrz 10y agoSomething like the following: void* pedanticmemmove(void *dst, const void *src, size_t n) { char buf[n > THRESHOLD ? 1 : n]; char *p = n > THRESHOLD ? xmalloc(n) : buf; memcpy(p, src, n); memcpy(dst, p, n); if (n > THRESHOLD) free(p); return dst; } But yeah, the alloca(3) variant is a bit nicer to look at and probably results in exactly the same code (but is non-standard, of course).
- kazinator 10y agoThe code to do what you describe is going to be nicer with alloca, because of the similarity between alloca and malloc. type *ptr = (nelem > THRESH) ? malloc(nelem * sizeof *ptr) : alloca(nelem * sizeof *ptr); /*...*/ if (nelem > THRESH) free(ptr);