谁能告诉我为什么此代码在删除时崩溃.

问题描述:

char * day =新的char [2];
char * tempMonth = NULL;
char * tempDay = NULL;
char temp [12];

strcpy_s(temp,sizeof(temp),"12-12");
tempDay = strtok_s(temp,-",& tempMonth);

strcpy_s(day,sizeof(day),tempDay);

delete [] day;

char *day = new char[2];
char *tempMonth = NULL;
char *tempDay = NULL;
char temp[12];

strcpy_s(temp,sizeof(temp),"12-12");
tempDay = strtok_s(temp,"-",&tempMonth);

strcpy_s(day,sizeof(day),tempDay);

delete[] day;

乍一看,我会说误解sizeof是您的问题. sizeof char *将为您提供指针的大小,即在32位系统上为4个字节.将4个字节复制到2个字节的缓冲区中,您很幸运能在delete []崩溃之前得到尽可能多的帮助:-)
检查文档中的sizeof.
At first glance I woud say misunderstanding sizeof is your problem. sizeof a char* will give you the size of a pointer, i.e. 4 bytes on a 32bit system. Copy 4 bytes into a 2 byte buffer and you''re lucky to get as far as the delete[] before it crashes :-)
Check the docs for sizeof.


请记住,字符串以零结尾!您应该始终在字符串末尾为\ 0保留一个字符.换句话说-更改:
Remember that strings are zero terminated! You should always reserve one more character for the \0 at the end of the string. In other words - change:
char *day = new char[2];


至:


to:

char *day = new char[3];


那应该做.

顺便说一句,我不同意strogg-恕我直言,即使没有要调用的析构函数,将new []与delete []配对也是一个好主意.


That should do it.

BTW I disagree with strogg - IMHO it''s always a good idea to pair new[] with delete[] - even if there are no destructors to call.