3 ms·
Then don't make it too big and fall back to malloc(3) above a certain threshold?
by slrz 10y ago
Then 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);