C strcpy()不会剪切char字符

时间:2013-12-09 13:29:28

标签: c++ strcpy

在Red Hat Linux上编写并运行下面的C ++代码后,我感到很惊讶。

#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

int main()
{
 char natureofGoods[17];
 char *name="sadasdasdasdas171212";

 strcpy(natureofGoods,name);

 cout<<natureofGoods<<endl;
}

我会在这里输出“sadasdasdasdas17”,因为natureofGoods有17个字符大小。但我把整个字符串作为输出。我的意思是“sadasdasdasdas171212asdadsfsf” 如果我在Visual Studio上运行此代码,那么在我等待时,我的程序会因调试消息而崩溃。为什么strcpy没有从17中删除名称字符,然后复制到natureofGoods

natureofGoods如何存储比其大小更多的特征?

3 个答案:

答案 0 :(得分:10)

strcpy尝试从源中复制字符,直到达到空终止符 - '\0'。你违反了这个合同,因为natureofGoods不够大,因此遇到了未定义的行为。

使用std::string !!!!!!!!!!

答案 1 :(得分:1)

strcpy source 字符串中的数据耗尽之前没有完成(即它命中空终止符)。因此,如果预先分配的目标字符串不够大,则可以发出 undefined behavour

考虑使用strncpy代替,在这方面,更安全。

答案 2 :(得分:0)

http://www.cplusplus.com/reference/cstring/strcpy/

  

将source指向的C字符串复制到指向的数组中   destination,包括终止空字符(并停止在   那一点)。

     

为避免溢出,目的地指向的数组大小   足够长,可以包含与源相同的C字符串(包括   终止空字符),并且不应该在内存中重叠   源。

相关问题