C++ 无法删除 char*,不断破坏堆

标签 c++ delete-operator

语言:C++,编译器:MSVS (/Za) 和 g++(是的,它必须适用于两者),级别:初学者

我正在尝试从 char* 中删除数据,以便我可以重新分配它并继续我的程序。我创建了一个新的 char*,将命令行参数的值分配给它,进行一些验证,然后如果验证失败,它应该释放 char* 并让我将新数据分配给 var,但是我得到了一个“堆检测到损坏”Visual Studio 中的错误。我很好奇我当前代码的修复以及任何其他可以更清晰/简洁地完成此操作的方法。

在 main() 中:

//...
//make non constant versions to be messed with
char* ba = new char[ strlen(argv[4]) + 1 ];
char* num = new char[ strlen(argv[2]) + 1 ];

//make non constant versions of commandline stuff
nonConstant( argv[4], argv[2], ba, num );

//do the conversion and printing
convert( ba, num );
//...

convert 这样做:

//...
if( error ) {
    getNew(ba, num, &error);
}
//...

这里是 getNew:

void getNew( char* ba, char* num, bool error ) {

//if there's an error in their numbers let them input new stuff and check to see if that's valid
while( error ) {
    //tell the user that the input was bad an prompt for more, use getline because strings are weird
    //cin stuff here (this part works, no problems)

    //free up base and num so I can reassign them
    delete[] ba; //<--this line fails
    delete[] num;

    //set lengths = to lengths of input + 1 for \0
    ba = new char[ inputBa.length() + 1 ];
    num = new char[ inputNum.length() + 1 ];

    //do the assignment of new input back to base and num
    inputBa.copy( ba, inputBa.length(), 0 );
    inputNum.copy( num, inputNum.length(), 0 );

    //ensure that the input was good this time
    validateInput( ba, num, error );
}

最佳答案

停止!立即切换到 std::string

这将根据要求修复您的代码,并且更加清晰/简洁。

关于C++ 无法删除 char*,不断破坏堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850633/

相关文章:

c++ - mcrypt linux 如何使用 rijndael 256 cbc

c++ - 在 C++ 中调试程序时出现空白屏幕

c++ - 查找并行化 C/C++ 的第 n 个排列

c++ - 为什么在析构函数中抛出异常时不调用重载删除?

c++ - 运算符为自己的字符串重载 (+=,=)

c++ - imshow() 在 C++ 中使用 OpenCV 3.2 产生奇怪的结果

c++ - 将包含不可复制/可移动对象的结构添加到 std::map

javascript - jQuery 'delete' 运算符还会删除先前设置的对象

c++ - 如何清除堆上分配的未使用数组的整个内存

c++ - 复制/move 省略与显式删除的复制/move 构造函数