C++ Valgrind 无效删除动态数组

C++ Valgrind invalid delete dynamic array

int* doubleArray(int *ptr, int n){
delete[]  ptr; 
int size = 2*n;
int * tmp = new int[size];
ptr = tmp;
delete [] tmp;
return ptr;
}

当我 运行 此代码将数组的大小加倍时,它以分段错误结束,当我 运行 Valgrind 时,它显示此消息:

Invalid free() / delete / delete[] / realloc()
==96889==    at 0x4A08634: operator delete[](void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==96889==    by 0x400C9E: doubleArray(int*, int) (debug.cpp:55)
==96889==    by 0x400B58: main (debug.cpp:34)
==96889==  Address 0xfff000300 is on thread 1's stack
==96889==  in frame #0, created by operator delete[](void*)

这是程序输出:

75 0 760281175 52 1621398400  
*** Error in `./debug': free(): invalid pointer: 0x00007ffd60a49258 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3427c77a8d]
/lib64/libc.so.6(cfree+0x5cd)[0x3427c83d2d]
./debug[0x400cd8]
./debug[0x400b99]
/lib64/libc.so.6(__libc_start_main+0xf0)[0x3427c20700]
./debug[0x400a29]

这里我初始化了从main

调用的第一个数组
int* ptr = initArray(n);

int* initArray(int n){
int arr[n];
int *ptr = arr;
return ptr;
}

关于如何修复此泄漏的任何想法?

您正在 return 指向您刚刚通过调用 delete 释放的内存。所以当你访问内存地址 returned 这个函数时,你可能会遇到分段冲突。

您可能应该将代码更改为以下内容

int* doubleArray(int *ptr, int n){
    int* new_array = new int[n << 1]; // n << 1 == 2*n
    for (int i = 0; i < n; ++i) {
        new_array[i] = ptr[i];
    }
    delete[]  ptr; 
    return new_array;
}

这将分配内存,复制旧数组和return一个指向容量是旧数组两倍的数组的指针。