今天测试同学反馈程序 出core了,看了下是snprintf出core,一般这个是不会出core,研究了下,原来是这样
网上的示例代码:
const int size = 10;
char dest[size+1];
char *source = "%26tn";
snprintf(dest, size,source);
snprintf(dest, size,"%s", source);
为什么呢,如果省略了“%s”,而后面的source中又有%时,snprintf认为source是格式化字符,这样编译时不出错,运行时出错
还有下面的NOTES看出 glibc 2.0.6及其以前 截断输入字符时返回-1,而后面的版本是返回实际写入了多少字符
NOTES
The glibc implementation of the functions snprintf and vsnprintf conforms to the C99 standard, i.e., behaves as
described above, since glibc version 2.1. Until glibc 2.0.6 they would return -1 when the output was truncated.