Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 556
fnisi Avatar asked May 29 '14 01:05

fnisi


1 Answers

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');
like image 133
Brian Bi Avatar answered Oct 02 '22 08:10

Brian Bi