野指针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;    //不会出问题
}
相关推荐
万法若空3 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商4 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫4 小时前
C++之string(OJ练习)
开发语言·c++·stl
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 199. 二叉树的右视图 | C++ DFS 逆序遍历
c++·leetcode·深度优先
-Marks-4 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本
CoderCodingNo5 小时前
【信奥业余科普】C++ 的奇妙之旅 | 12:程序的交互与加工——数据的输入与算术运算
开发语言·c++
yx868xy5 小时前
Cuda加速直线拟合
c++·cuda
蜗牛在听雨5 小时前
基于 C++ 的 UG/NX 二次开发环境配置
c++·二次开发·ug
SimpleLearingAI6 小时前
C++虚函数详解
开发语言·c++