Search code examples
arrayscstringcharconcatenation

String unwanted character in c


I am trying to add integers to a string. When I debug my code everything works perfectly fine, but when i run it normally two unwanted characters are being printed at the beginning of the string. How do I avoid this?

    int number_of_ints = 5;
    char s[number_of_ints*2];
    char suffix[4];
    for(int i = 1; i <= number_of_ints; i++){
        snprintf(suffix, number_of_ints, "%d*", i);
        strncat(s, suffix, 2);
        printf("%s\n", s);
    }

This is the output when building and running the code normally.

`û1*
`û1*2*
`û1*2*3*
`û1*2*3*4*
`û1*2*3*4*5*

Solution

  • Strings in C are a sequence of nonzero bytes followed by a terminating byte with a value of zero (the null-terminating byte, '\0').

    You must size your buffer to have an additional space, to guarantee room for this null-terminating byte.

    You must additionally make sure the contents of the buffer contain a valid string. You can do this by setting the first element of the buffer to the null-terminating byte, creating a zero-length string.

    Failing to initialize the contents of your buffer means it will contain indeterminate values, and passing such a buffer to a function expecting a valid string will invoke Undefined Behavior.

    The second argument to snprintf should be, at most, the size of the destination buffer.

    Finally, consider using size_t when applicable, as it is the appropriate type for dealing with memory sizes (e.g., sizing variable-length arrays; the sizeof operator resolves to this type; snprintf expects this type as its second argument).

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        size_t number_of_ints = 5;
        char s[number_of_ints * 2 + 1];
        char suffix[4];
    
        s[0] = '\0';
    
        for (size_t i = 1; i <= number_of_ints; i++) {
            snprintf(suffix, sizeof suffix, "%zu*", i);
            strncat(s, suffix, 2);
            printf("%s\n", s);
        }
    }