snprintf做字符串连接时的坑

原创内容,转载请注明出处

Posted by Weakyon Blog on October 29, 2014

fastdfs的后台监控程序里有一段关于字符串解析的操作,使用snprintf进行字符串连接后无论如何解析的字串都是错误的

snprintf(buf,1024,”%s%s”,buf);

问题出在这一句,因为sprintf系列比起strcat方便很多而且更加灵活,所以我一直使用sprintf来进行字符串的连接操作,没想到用snprintf就跪了。

后来用sprintf就没问题了

看了一下man

  
Some programs imprudently rely on code such as the following

	sprintf(buf, "%s some further text", buf);

to  append  text  to  buf.  However, the standards explicitly note that the results
are undefined if source and destination buffers overlap when calling sprintf(),
snprintf(), vsprintf(), and vsnprintf().  Depending on the version of gcc(1) used,
and the compiler options employed, calls such as the above will not produce  the
expected results.
The  glibc  implementation  of the functions snprintf() and vsnprintf() conforms to 
the C99 standard, that is, behaves as described above, since glibc version 2.1.
Until glibc 2.0.6 they would return -1 when the output was truncated.

原来用sprintf,src和des相同指针时是未定义的行为,在linux的gcc下sprintf可以完成这个操作,然而snprintf不行

所以安全的字符串连接操作方式,还是应该存在一个缓冲区

  
buf[512];
temp_buf[512];
strncpy(temp_buf,buf,sizeof(buf));
snprintf(buf,sizeof(buf) + strlen("123"),"%s%s",temp_buf,"123");
29 Oct 2014