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;
}
关于如何解决此漏洞的任何想法?
答案 0 :(得分:1)
您正在返回一个指向您刚刚通过调用delete
解除分配的内存的指针。因此,当您访问此函数返回的内存地址时,您可能会遇到分段违规。
您应该将代码更改为以下
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;
}
这将分配内存,复制旧数组并返回指向数组的指针,该数组的容量是旧数组的两倍。