I want to use mysprintf () instead of sprintf () for automatic buffer size allocation.
Is there any problem with mysprintf()? Or can you recommend a better way?
char s[256]; sprintf(s, "%s-%s-%s", "abcdefg", "abcdefg", "abcdefg"); string s = mysprintf("%s-%s-%s", "abcdefg", "abcdefg", "abcdefg"); string mysprintf(const char* format, ...) { int ret; char* buf; va_list ap; va_start(ap, format); ret = vasprintf(&buf, format, ap); va_end(ap); if (ret == -1) { return {}; } string out(buf); free(buf); return out; }
sprintfwith little to show for it. Has anyone introduced you to parameter packs? This will still be painful as all hell, but type safe.std::string's constructor throws, you've leaked memory.bufin astd::unique_ptrwith a custom deleter to callfree()vasprintf()is GNU specific. If your compiler is compatible with C99 - or supports the C99 standard library - you can usevsnprintf()to, (1) obtain a required buffer (2) allocate a container (std::stringor astd::vector<char>) of appropriate size and (3) write the data directly to that container. The benefit of this alternative is that all the allocations are cleanly deallocated (no need to callfree()manually, and no opportunity to inadvertently not do so).