Learn note(cpp): take care when use new in a code block.

来源:互联网 发布:域名报毒查询 编辑:程序博客网 时间:2024/06/12 04:18

When I want to write a program to store the hash code of a file into a hash table, I find that whenever I expend the table and call the delete in the second time, an error: “double free” will occur.
HashNode* ht = new HashNode[len];
while(....){
if (overload(size)){
delete [] ht;
len = update(len);
HashNode* ht = new HashNode[len];
....
}
....
}

Just at the moment I call the delete at the second time, the error occurred.

Actually, it was my fault.
I’ve ignored the
type* var = new type;
is the same as
type* var;var = new type;
Yeah, this means I have to declare first, and then distribute the memory.
so the
HashNode* ht = new HashNode[len];
is not safe to use, because the ht I declared in “if ” will be released exactly after this block. Of cause the double free will occur.

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机屏局部失灵怎么办 iphone8触屏不灵敏怎么办 苹果机8屏幕失灵怎么办 车钥匙丢车上怎么办 指纹锁华盖坏了怎么办 非法入了户口怎么办 司考成绩单丢了怎么办 小饭桌转让手续怎么办 两个领导不和你怎么办 两个领导意见不一致怎么办 两个领导对立我怎么办 投诉申通没用怎么办 领导作风有问题怎么办 做完火疗受风了难受怎么办 鼻子做的不好看怎么办 埋线双眼皮出血怎么办 割完双眼皮出血怎么办 全切双眼皮出血怎么办 割双眼皮出血了怎么办 割双眼皮后出血怎么办 双眼皮手术后出血怎么办 缝双眼皮开了怎么办 朋友网没了怎么办 压疮发生后怎么办 学籍账号已登录怎么办 护士学分不达标怎么办 高中学籍错了怎么办 定时器时间太短不够用怎么办? 考试时间不够用怎么办 感觉时间不够用怎么办 学习时间不够用怎么办 天天时间不够用怎么办 网贷骚扰通讯录怎么办 老被电话骚扰怎么办 对付广场舞噪音怎么办 普法平台考试不及格怎么办 假疫苗事件孩子怎么办 网上办生育证怎么办? 新生儿足跟血筛查没通过怎么办 新生儿听力筛查未通过怎么办 医药代表业绩差怎么办