分析 snprintf sprintf printf 等 类“printf” 格式化输出函数,由于类型不兼容造成的内存混乱

分析 snprintf sprintf printf 等 类“printf” 格式化输出函数,由于类型不兼容造成的内存混乱

1、引言

在c/c++中有关字符串的格式输出的方法,一般都采用类“printf”系列函数,文件:fprintf 缓存区:sprintf snprintf 标准输出:printf ,在使用这些函数时要保证 变量和输出的格式要严格保持一致,否则将会出现莫名其妙的问题。c++11有关文档对此进行说明:

if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:

 — one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types; 

— one type is pointer to void and the other is a pointer to a character type.

由此我们可以知道,用类型不匹配的占位符格式化输出一个变量的行为是未定义的(int类型与unsigned int类型以及指向void类型的指针类型和指向字符型的指针类型除外),下面我们就来分析这种未定义的行为

接下来我们将进行重点的讨论,并且给出相关的示例程序

2、有sprintf引发的栈溢出问题

//暂时写到这里会继续更新

发布了67 篇原创文章 · 获赞 15 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/wanxuexiang/article/details/90050432