Search code examples
cc-stringsnull-terminatednul

*char ending with double '\0'


My code is crashing because of a lack of the char '\0' at the end of some strings.

It's pretty clear to me why we have to use this termination char. My question is, is there a problem adding a potential 2nd null character to a character array - to solve string problems?

I think it's cheaper just add a '\0' to every string than verify if it needs and then add it, but I don't know if it's a good thing to do.


Solution

  • is there a problem to have this char ('\0') twice at the end of a string?

    This question lacks clarity as "string" means different things to people.
    Let us use the C specification definition as this is a C post.

    A string is a contiguous sequence of characters terminated by and including the first null character. C11 §7.1.1 1

    So a string, cannot have 2 null characters as the string ends upon reaching its first one. @Michael Walz

    Instead, re-parse to "is there a problem adding a potential 2nd null character to a character array - to solve string problems?"


    A problem with attempting to add a null character to a string is confusion. The str...() functions work with C strings as defined above.

    // If str1 was not a string, strcpy(str1, anything) would be undefined behavior.
    strcpy(str1, "\0");  // no change to str1
    
    char str2[] = "abc";
    str2[strlen(str2)] = '\0'; // OK but only, re-assigns the \0 to a \0
    // attempt to add another \0
    str2[strlen(str2)+1] = '\0'; // Bad: assigning outside `str2[]` as the array is too small
    
    char str3[10] = "abc";
    str3[strlen(str3)+1] = '\0'; // OK, in this case
    puts(str3);                  // Adding that \0 served no purpose
    

    As many have commented, adding a spare '\0' is not directly attending the code's fundamental problem. @Haris @Malcolm McLean

    That unposted code is the real issue that need solving @Yunnosch, and not by attempting to append a second '\0'.