You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现动态扩容数组时内存分配触发Segmentation fault求助

问题根因

段错误由多重内存操作错误叠加导致,核心问题如下:

  • 构造函数未初始化_collection指针,该指针为野指针,首次调用append时对野指针执行delete操作,直接触发非法内存访问。
  • 动态数组释放语法错误,你使用delete释放new[]分配的数组,应该用delete[],二者不可混用,否则会触发未定义行为。
  • 首次调用append时,temp指向野指针,后续for循环读取temp[i]属于非法内存访问。

修复代码

1. 修改构造函数(IntegerCombination.cpp)

IntegerCombination::IntegerCombination()
{
    _length = 0;
    _collection = nullptr; // 显式初始化指针为空
}

2. 修改append函数(IntegerCombination.cpp)

void IntegerCombination::append(int val)
{
    int newValPos = _length;
    int* temp = _collection;
    
    // 仅非空指针需要释放,且数组用delete[]释放
    if (temp != nullptr) {
        delete[] temp;
    }

    _length++;
    _collection = new int[_length];
    
    // 旧数组非空时才需要拷贝元素
    if (temp != nullptr) {
        for(int i = 0; i < newValPos; i++) {
            _collection[i] = temp[i];
        }
    }
    _collection[newValPos] = val;
}

补充优化建议

  • 建议给IntegerCombination基类添加虚析构函数,负责释放_collection内存,避免子类对象销毁时发生内存泄漏。
  • 日常开发优先使用标准库std::vector实现动态数组,不需要手动管理内存,可大幅降低这类错误出现的概率。

内容的提问来源于stack exchange,提问作者Andog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:15:03