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

自定义vector类实现出现Segmentation Fault问题求助

自定义vector类段错误的核心问题及修复方案

核心问题分析

  • 野指针导致的内存访问错误
    在new_allocation函数中,你刚将新分配的temp地址赋值给arr,就立刻执行delete[] temp,这会让arr指向一块已经被操作系统回收的内存空间。后续对arr的任何读写操作都是访问野指针,必然触发段错误。

  • 默认构造函数未初始化指针
    默认构造函数里仅初始化了s和c为0,但arr指针未被设置为nullptr。当调用push_back时,由于s == c(0等于0)会进入new_allocation,此时循环中访问arr[i]会读取野指针指向的未知内存,引发未定义行为。

修复后的完整代码

#include <iostream>
using namespace std;

template <typename T> class vector{
    T *arr;
    int s;
    int c;
    void new_allocation(){
        T *temp = new T[s + 10];
        c = s + 10;
        for (int i = 0; i < s; i++)
            temp[i] = arr[i];
        delete[] arr; // 释放旧内存,避免泄漏
        arr = temp;
    }
    public:
        vector() : arr(nullptr), s(0), c(0) {} // 初始化arr为nullptr
        vector(int userVectorSize){
            s = c = userVectorSize;
            arr = new T[userVectorSize];
        }
        void push_back(T data){
            if (s == c)
                new_allocation();
            arr[s] = data;
            s++;
        }
        T& operator[](int index){ return arr[index]; } // 返回引用支持修改
        const T& operator[](int index) const { return arr[index]; } // const版本
        int size() const { return s; } // 改为const成员函数
};

int main(){
    int n, m;
    cin >> n >> m;
    vector<int> graph[n + 1];

    for (int i = 0; i < m; i++){
        int v1, v2;
        cin >> v1 >> v2;
        graph[v1].push_back(v2);
        graph[v2].push_back(v1);
    }

    for (int i = 1; i <= n; i++){
        cout << i << " -> ";
        for (int k = 0; k < graph[i].size(); k++)
            cout << graph[i][k] << " ";
        cout << endl;
    }
}

额外优化说明

  1. 在new_allocation中补充delete[] arr,避免每次扩容时旧内存无法释放导致内存泄漏。
  2. 将operator[]修改为返回引用,支持通过下标修改vector内的元素,同时添加const版本适配const对象访问。
  3. 将size()改为const成员函数,符合C++的const正确性原则。

内容的提问来源于stack exchange,提问作者Pratik Tushar Cholke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:54:29