Chinaunix

标题: 请教一个溢出相关的问题 [打印本页]

作者: nullplace    时间: 2009-05-02 10:34
标题: 请教一个溢出相关的问题
下面这段代码,存在溢出问题。
假如s1、s2是数组的话,倒是可以把11、12行改成strncpy(s1, str1, sizeof(s1));strncpy(s2, str2, sizeof(s2));
现在是指针,请问怎么改合适呢?谢谢。

     1  #include <stdio.h>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2  #include <string.h>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4  void foo(char *s1, char *s2);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;6  void foo(char *s1, char *s2)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;7  {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;8      char *str1 = "foobar";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9      char *str2 = "hello, world";
&nbsp;&nbsp;&nbsp;&nbsp;10
&nbsp;&nbsp;&nbsp;&nbsp;11      strcpy(s1, str1);
&nbsp;&nbsp;&nbsp;&nbsp;12      strcpy(s2, str2);
&nbsp;&nbsp;&nbsp;&nbsp;13  }
&nbsp;&nbsp;&nbsp;&nbsp;14
&nbsp;&nbsp;&nbsp;&nbsp;15  #define BUF_SZ 8
&nbsp;&nbsp;&nbsp;&nbsp;16
&nbsp;&nbsp;&nbsp;&nbsp;17  int main(void)
&nbsp;&nbsp;&nbsp;&nbsp;18  {
&nbsp;&nbsp;&nbsp;&nbsp;19      char a1[BUF_SZ];
&nbsp;&nbsp;&nbsp;&nbsp;20      char a2[BUF_SZ];
&nbsp;&nbsp;&nbsp;&nbsp;21
&nbsp;&nbsp;&nbsp;&nbsp;22      foo(a1, a2);
&nbsp;&nbsp;&nbsp;&nbsp;23      printf("a1 = '%s'\n", a1);
&nbsp;&nbsp;&nbsp;&nbsp;24      printf("a2 = '%s'\n", a2);
&nbsp;&nbsp;&nbsp;&nbsp;25
&nbsp;&nbsp;&nbsp;&nbsp;26      return 0;
&nbsp;&nbsp;&nbsp;&nbsp;27  }

作者: daybreakcx    时间: 2009-05-02 10:45
顺带把长度当作参数一起传入foo
作者: xinglp    时间: 2009-05-02 10:53
传入长度,用strncpy()




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2