语言: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/