Search code examples
cdynamicstaticallocation

Returning a string properly in C, multiple times


OK, the following way to return a string works fine:

char* SU(double V) {
    static char Str[80];
    // Do something
    return Str;
}
printf("%s", SU(A));

But the following will fail silently because the string space in memory is the same at the end of both calls:

printf("%s %s", SU(A), SU(B));

How can I do this cleanly and simply ? I was looking at alloca() but I don't think I can return a string allocated with alloca(), can I ?


Solution

  • Effectively, all current C compilers support compound literals and inline functions. Together it is possible to write thread-safe, memory-safe implementation that does not rely on static buffers (that can lead to unexpected bugs).

    Basic idea is to combined a function that uses caller provided buffer, with a macro to abstract the creation of this temporary buffer. Negligent performance/memory impact for most applications.

    For example - for the case of return the string-ified version of the a number the following itoa function can be implemented with macro/wrapper/inline function.

    The limitation is that the wrapper need a way to estimate the size of returned string.

    #include <stdio.h>
    
    const char *itoa_wrapper(char *buffer, int buffer_sz, int val)
    {
            int result = snprintf(buffer, buffer_sz, "%d", val) ;
                    // Assuming formatting always works
            return buffer ;
    }
    
    
    #define itoa(val) itoa_wrapper( (char[20]) {}, 20, val)
    
    int main(int argc, char **argv)
    {
            printf("ARGC=%s, 1+2+3+4=%s\n", itoa(argc), itoa(1+2+3+4)) ;
    }