我有下面的代码:
#include<iostream>
using namespace std;
void test(char arr[], int size){
char* newA = new char[5];
delete[] arr; // this line cause the breakpoint
arr = newA;
}
void main(){
char* aa = new char[5];
test(aa,5);
aa[0] = 's';
}
当我运行这段代码时,我看到索引 0 处的变量“aa”为“s”,然后断点被触发。
最佳答案
你正在按值传递 arr
,所以这一行
arr = newA;
在调用方没有影响。所以你在这里从一个已删除的数组中读取:
aa[0] = 's';
这是未定义的行为。您可以通过三种方式解决此问题:
传递引用:
void test(char*& arr, int size) { .... }
返回指针:
char* test(char* arr, int size) {
delete[] arr;
return new char[5];
}
或者,更好的是,使用行为良好的标准库类型,例如 std::string
。
关于c++ - 删除一个 char 数组指针会触发一个神秘的断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208134/