删除一个char数组指针会触发一个神秘的断点

时间:2014-01-18 18:30:22

标签: c++ visual-studio debugging pointers breakpoints

我有下面的代码:

#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',然后触发断点。

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

1 个答案:

答案 0 :(得分:4)

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