8月 2021

C/C++格式化字符串的一个小坑

格式化字符串是个写C/C++代码是很常见的东西,例如下面这段用了printf的简单代码:

#include <string>

int main()
{
    std::string test = "hello world!";
	printf("%s", test.c_str());
    return 0;
}

虽然看起来有点怪,混用了C++的string和C的printf输出,其实换成char *也是可以的,不过,这并不重要,重要的是我有时会偷懒把上面这段代码写成这样:

#include <string>

int main()
{
    std::string test = "hello world!";
	printf(test.c_str());
    return 0;
}

这样写,看起来似乎输出没有问题,两份代码的结果都是输出”hello world!”,并没有什么区别,那标题说的坑到底在哪呢?考虑这种情况,我们的test字符串里放的不再是简单的 hello world! 了,而是比如转义过的URL串,如“http://www.baidu.com/测试”会被转义成“http%3A%2F%2Fwww.baidu.com%2F%E6%B5%8B%E8%AF%95”,此时如果再用偷懒的写法,直接printf这个字符串,显而易见的就会出问题了!

Continue reading…