c++gccg++warnings

How to fix gcc -Wall "embedded '\0' in format" warning


This may not be very crucial, however I am trying to fix all the warnings g++ is complaining about. In the code below, I am getting "embedded '\0' in format" warning for the snprintf() line.

How can I fix this?

    int filePathSize = path.size() + s.size() + 1;
    char filePath[filePathSize];
    snprintf(filePath,filePathSize,"%s%s\0",path.c_str(),s.c_str());

Thanks in advance...


Solution

  • The warning is there for a good reason: snprintf is going to think the \0 marks the end of the string. If you actually need a null to be printed, you can't embed it directly into the string; C strings cannot contain null characters for this very reason. This is the most obvious workaround:

    snprintf(filePath,filePathSize,"%s%s%c",path.c_str(),s.c_str(),'\0');
    

    Adding the null terminator manually is not needed, as snprintf always includes the \0 automatically (see the manpage).