strncpy越界

参考:http://www.iteye.com/topic/202588

 

strncpy(dest, src, n);似乎是安全的函数

原型:

char *strncpy(char *restrict s1, const char *restrict s2, size_t n);

 

今天碰到了问题,是由于对strncpy理解不够造成的

 

man里:

If the array pointed to by s2 is a string that is shorter than n bytes, null bytes shall be appended to the copy in the array pointed to by s1, until n bytes in all are written.

 

事实上s2往往不如n那么长,于是s1剩余部分会全填0。今天碰到的问题就是,s1的长度不如n,但是dest指向的n的长度全部被改写,于是内存被越界写了0,程序挂掉了。

 

这或许不算strncpy的bug,只是之前设计的函数接口,没有传入dest的长度,而使用了定值n在strcpy中,自己的设计问题。

 

结论:dest一定要和n长度匹配。

posted @ 2012-04-13 10:55  mosakashaka  阅读(279)  评论(0编辑  收藏  举报