Well, that should be `snprintf()` to start with, but even with that, there are issues. The return type of `snprintf()` is `int`, so it can return a negative value if there was some error, so you have to check for that case. That out of the way, a positive return value is (and I'm quoting from the man page on my system) "[i]f the output was truncated due to this limit then the return value is the number of characters which would have been written to the final string if enough space had been available." So to safely use `snprintf()` the code would look something like:
int size = snprintf(NULL,0,"some format string blah blah ...");
if (size < 0) error();
if (size == INT_MAX)
error(); // because we need one more byte to store the NUL byte
size++;
char *p = malloc(size);
if (p == NULL)
error();
int newsize = snprintf(p,size,"some format string blah blabh ... ");
if (newsize < 0) error();
if (newsize > size)
{
// ... um ... we still got truncated?
}
Yes, using NULL with `snprintf()` if the size is 0 is allowed by C99 (I just checked the spec).
One thing I've noticed about the C standard library is that is seems adverse to functions allocating memory (outside of `malloc()`, `calloc()` and `realloc()`). I wonder if this has something to do with embedded systems?
One thing I've noticed about the C standard library is that is seems adverse to functions allocating memory (outside of `malloc()`, `calloc()` and `realloc()`). I wonder if this has something to do with embedded systems?