sprintf() with automatic memory allocation?

Here is the original answer from Stack Overflow. As others have mentioned, you need snprintf not sprintf. Make sure the second argument to snprintf is zero. That will prevent snprintf from writing to the NULL string that is the first argument.

The second argument is needed because it tells snprintf that enough space is not available to write to the output buffer. When enough space is not available snprintf returns the number of bytes it would have written, had enough space been available.

Reproducing the code from that link here …

char* get_error_message(char const *msg) {
    size_t needed = snprintf(NULL, 0, "%s: %s (%d)", msg, strerror(errno), errno) + 1;
    char  *buffer = malloc(needed);
    sprintf(buffer, "%s: %s (%d)", msg, strerror(errno), errno);
    return buffer;
}

Leave a Comment