谁能告诉我为什么此代码在删除时崩溃. [英] Can anybody tell me why this code crashes at delete.

查看:62
本文介绍了谁能告诉我为什么此代码在删除时崩溃.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.


这篇关于谁能告诉我为什么此代码在删除时崩溃.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆