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

传递std::vector<std::string>*到函数触发std::bad_alloc错误,求排查

问题分析与修复

你的代码存在两个关键问题,其中一个可能是触发std::bad_alloc的诱因:

1. 无意义的动态分配引发内存泄漏与潜在内存耗尽

你先通过new创建了一个std::vector<std::string>对象,随后立刻将指针v重新指向传入的p_completeList,这导致new出来的vector永远无法被释放,造成内存泄漏。如果程序多次调用该函数,会持续消耗内存,最终可能因系统内存耗尽触发std::bad_alloc异常。

2. 未校验传入指针的合法性

如果调用split_List时传入的是空指针(nullptr),那么v->size()会触发未定义行为,这种非法内存访问可能破坏堆结构,间接引发std::bad_alloc异常。

修复后的代码

void split_List(std::vector<std::string>* p_completeList) {
    // 先校验指针是否合法
    if (!p_completeList) {
        return; // 可根据实际需求调整空指针处理逻辑
    }

    // 无需额外动态分配,直接使用传入的指针
    std::vector<std::string>* v = p_completeList;

    // 使用size_t类型循环,避免int与size()类型不匹配的溢出风险
    for (size_t i = 0; i < v->size(); ++i) {
        std::string value = (*v)[i];
        // ...do some splitting, printing with value
    }
}

更优写法(推荐)

直接使用引用替代指针,既能避免空指针风险,代码也更简洁安全:

void split_List(std::vector<std::string>& completeList) {
    // 范围for循环遍历,代码更直观
    for (const auto& value : completeList) {
        // ...do some splitting, printing with value
    }
}

调用时直接传入vector对象即可:split_List(myVector);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:07