【发布时间】:2013-12-31 02:07:12
【问题描述】:
语言: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 );
}
【问题讨论】:
-
编译时启用提示和警告。
-
如果
getNew的参数error声明为bool类型,为什么getNew调用中对应的参数看起来像&error???我的意思是它可能在形式上是正确的,因为指针可以转换为bool类型。但是,这里的想法是什么? -
@KenWhite,我该怎么做?
标签: c++ delete-operator