野指针bug

cpp 复制代码
RunUnit *UnitList[10000];
void aaaa()
{
    //用cu接收
    RunUnit *cu = UnitList[Index];

    /*
        利用UnitList[Index]中的数据,借助用cu做一系列的动作
    */

    //UnitList[Index]中的数据之后在哪都不再使用,这里把它销毁
    delete cu;
    cu = nullptr;
}

void bbbb()
{
    if(UnitList[Index] == nullptr)
    {
        continue;
    }

    int c = 0;        //会走到这里
    UnitList[Index].index = 0;    //会出问题
}

解释:cu和UnitList[Index]都指向同一块地址,他们在栈上的不同位置;

delete cu; :将堆上的地址给清掉;

但cu和UnitList[Index]都还是有值的,只是指向的地址没有数据;所以下次去判断UnitList[Index] == nullptr不会通过,会继续往下,那利用到这块堆上的时候就有问题了;

cpp 复制代码
RunUnit *UnitList[10000];
void aaaa()
{
    //用cu接收
    RunUnit *cu = UnitList[Index];

    /*
        利用UnitList[Index]中的数据,借助用cu做一系列的动作
    */

    //UnitList[Index]中的数据之后在哪都不再使用,这里把它销毁
    delete cu;
    UnitList[Index] = nullptr;   
}

void bbbb()
{
    if(UnitList[Index] == nullptr)
    {
        continue;
    }

    int c = 0;        //不会走到这里
    
    UnitList[Index].index = 0;    //不会出问题
}
相关推荐
xlp666hub17 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网19 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub21 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星21 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus5 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit7 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_8 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++