首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

诚心发问:有关strcpy,strcpy_s,strncpy,strncpy_s解决方法

2012-05-20 
诚心发问:有关strcpy,strcpy_s,strncpy,strncpy_s字符串的复制问题:我已经查阅过资料:strcpy_s是VS后续版

诚心发问:有关strcpy,strcpy_s,strncpy,strncpy_s
字符串的复制问题:
  我已经查阅过资料:
strcpy_s是VS后续版本中微软新推出的更安全的函数。
strcpy之所以不安全是因为它需要程序员保证输出buffer不会越界。

一个程序,
1.我用strcpy_s和strncpy_s时,编译通过,未出现warning,运行时出现了bug:the buffer is too small!
(保证函数调用肯定是没错的,可又找不出错,显然是内存分配上有问题)!

2.如果用strcpy或strncpy时,编译时出现warning,当然我知道出现warning的原因.可是运行时没出现bug!

因为我是运用在文本文件处理当中,所以我可以直接打开文件,观看是否复制成功,2.的复制没有差错

出现上述情况,我有若干问题:
  a.出现1情况的Bug一般是什么原因,怎么找出
  b.对于2中的warning可以忽视它吗?既然能够复制成功,不是就没问题了吗?会对后面一些操作有什么影响
  c.怎么查看buffer越界,越界后怎么办?

麻烦大家了!!!

[解决办法]
#pragma warning(disable:4996)
在最后一个字节的后面对应内存地址处设置内存值改变断点:
Setting a Breakpoint When the Value at a Specified Memory Address Changes
To break when the value at a specified memory address changes 

From the Edit menu, click Breakpoints.
Click the Data tab of the Breakpoints dialog box.
In the Expression text box, type the memory address for the byte. 
For a word or doubleword memory address, enclose the address in parentheses, and precede it with a cast operator. For example, WO(21406036) for the word at memory location 21406036. Use the cast operator BY for a byte (optional), WO for a word, or DW for a doubleword. (The debugger interprets all integer constants as decimal unless they begin with zero (0) for octal or zero and x (0x) for hexadecimal.)
In the Number Of Elements text box, type the number of bytes, words, or doublewords to monitor. If you used the BY operator in the Expression field, specify the number of bytes. If you used WO, specify the number of words. If you used DW, specify the number of doublewords. 
Click OK to set the breakpoint. 

[解决办法]
对于问题a(情况1),请给出完整的精简的程序。
问题b,情况2的越界错误是累积性的,对于你这种只运行一次的程序来说(或者越的不多),甚至也许看不出来异常,不过套用个话来说“出来混迟早要还的”,逻辑上该怎么做就怎么做,硬要违反规则(借口是看不出来错误,但是往往看不出来错误不代表没有错误,特别是逻辑/概念上的东西),后果自负。
问题c就是学会用debugger,不存在说越界后怎么办,而是要学会写不会越界的代码。

热点排行