删除char阵列指针触发了一个神秘的断点



我有下一个以下代码:

#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';
}

当我运行此代码时,我会看到索引零的变量" aa"是's',然后触发了断点。

https://i.stack.imgur.com/pzcw6.png

您正在按值传递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

最新更新