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

标签 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';
}

当我运行这段代码时,我看到索引 0 处的变量“aa”为“s”,然后断点被触发。

http://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

关于c++ - 删除一个 char 数组指针会触发一个神秘的断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208134/

相关文章:

c++ - GetVolumeNameForVolumeMountPoint 返回 false

c++ - Serial Hexa 对话框(C++/Qt 5.0 的 python 代码)

c# - Visual Studio C# e.Location 错误

visual-studio - 用于构建 Visual Studio 项目的 PowerShell 脚本

android - Chrome 远程调试三星 Galaxy s4

Eclipse Debug View 在全屏模式下在断点处弹出

java - Phonegap 调试远程用户

c++ - 如何在 leetcode 中修复 "runtime error: reference binding to null pointer of type ' value_type' (STL_vector.h)”?

python - 遍历 boost::python vector 时出现 TypeError

c# - Visual Studio 改变了 Ctrl-K-D 的工作方式