boost::format 参数个数不匹配

在C语言中,如果字符串个数不匹配时,会导致内存信息泄露。Boost也提供了format的类用来处理格式化参数,对于格式化参数不匹配,boost的format会如何处理?首先,看一段代码:

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include<iostream>

using namespace std;

// 
void callBoostFormat1()
{
	cout <<  
		boost::format("Test: %05d, %.2f, %s, %x") 
		% 11111
		% 2222,0
		% "test"
		<<endl; 

}


int main(int argc, char **argv) 
{
	cout << "test begin " <<endl; 
	callBoostFormat1();
	cout << "test end " <<endl; 
	return 0;
}




gcc -o Test Test.cpp  得到可执行文件,执行结果是:

由此,可以知道,boost会针对参数不匹配的情况抛出异常,如果没有对异常进行处理,则终止程序继续进行运行。虽然boost的fomat不会导致内存信息泄露,但是,由于参数不匹配会抛出异常,进而导致程序异常终止,这也是不可以接受的。因此,无论使用什么库的什么API,都需要保证格式化字符串和参数个数的匹配,不能以接收到的字符串作为格式化参数的一部分,否则,格式化字符串就会被控制,导致安全问题发生。

发布了85 篇原创文章 · 获赞 9 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/jimmyleeee/article/details/100882638