delete数组报错

今天学数据结构,在孙弋教授lesson3内存管理,写了一段代码

#include <iostream>

using namespace std;

void memorisePractise() {
    int *tempIndicator = new int[10];
    for (int i = 0; i < 10; i++) {
        *tempIndicator= 2 * i;
        cout << *tempIndicator << endl;
        tempIndicator++;
    }
    delete []tempIndicator;
}

int main()
{
    memorisePractise();
    std::cout << "Hello World!\n";
}

这里发生的现象

1.执行delete[]语句时,程序直接弹窗,崩溃。
2.执行delete[]语句时,程序卡死。将delete语句注释掉,又正常了,但发生了内存泄露。

发生的原因是指针tempIndecator++无意中使指针中发生移动,不再指向数组的首地址

解决方法:

引入一个新的指针Indector,赋值为tempIndecator,使Indector移动

修改后的代码

#include <iostream>

using namespace std;

void memorisePractise() {
    int *tempIndicator = new int[10];
    int* Indicator = tempIndicator;
    for (int i = 0; i < 10; i++) {
        *Indicator= 2 * i;
        cout << *Indicator << endl;
        Indicator++;
    }
    delete []tempIndicator;
}

int main()
{
    memorisePractise();
    std::cout << "Hello World!\n";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值