News for hackers. Stuff that matters.
Re:Strlcpy and Strlcat – Consistent, Safe, String Copy and C... by tom_ on Tuesday April 25, 2023 @09:03AM (#35699876)
Here's something I've found a useful upgrade to asprintf, as it frees the passed-in buffer after expanding the format string. You can just pass the same char ** repeatedly (and also pass it as one of the string arguments corresponding to a %s!) and it'll update the pointer appropriately each time. Makes many kinds of string manipulation very simple.

    int xasprintf(char**p,const char *fmt,..) {
        int n=0;
        char *p2=nullptr;
        if(fmt) {
            va_list v;
            va_start(v);
            n=asprintf(&p2,fmt,v);
            va_end(v);
        }
        if(n>=0) {
            free(*p);
            *p=p2;
        }
        return n;
    }
If you thought asprintf was inefficient, this is worse. But it's very convenient!

There are no comments on this comment yet.