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

C++使用delete[]释放动态数组时报free(): invalid pointer错误求助

C++指针偏移后delete[]报错原因分析

核心错误原因

delete[] 运算符要求必须传入 new[] 返回的原始数组首地址,任何偏移后的指针传入delete[]都属于C++标准规定的未定义行为,没有任何可预期的执行结果。
你的代码中执行了++arr操作后,arr已经偏移了1个int长度的地址,不再指向new int[size]返回的起始位置,此时传入delete[]自然会触发内存释放错误。

不同平台表现差异的原因

  • 安卓端Bionic libc的内存分配器对free操作的校验逻辑相对宽松,即使传入偏移后的指针,也可能因为没有触发校验规则而看似正常运行,但这完全是不可靠的,属于“错误代码刚好跑通”的情况,不代表代码逻辑合法。
  • GCC配套的glibc对内存释放的校验更严格,会直接检测到传入的指针不是内存分配器返回的原始地址,因此主动抛出free(): invalid pointer错误,属于合理的问题提示。

正确实现方案

只需要保留原始首地址的备份,或者用临时指针做算术操作即可,示例代码如下:

#include <iostream>

int main()
{
    int *arr{};
    size_t size{};
    std::cout << "Please enter the size of the array you want to create: "; 
    std::cin >> size;
    arr = new int[size];
    // 用临时指针做运算,不修改原始arr
    int* tmp_ptr = arr;
    *(tmp_ptr + 0) = 5;
    *(tmp_ptr + 1) = 10;
    std::cout << "++tmp_ptr: " << ++tmp_ptr << " (pointer incrementation, we move by an int and tmp_ptr is now arr + 1)" << std::endl;  
    // 始终用原始首地址释放
    delete [] arr;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:24:04