[英]C++ error on delete[] after iterating through pointer
环境:Windows 7 pro x64,Microsoft Visual Studio 2015 Enterprise,版本14.0.25424.00更新3
int testFunction()
{
std::string _orig = "[188 80% (1/2)O:152]";
std::string _orig2 = "[999 99% (1/1)O:999]";
char *orig = NULL;
char *orig2 = NULL;
orig = new char[_orig.length() + 1];
strcpy(orig, _orig.c_str());
orig2 = new char[_orig2.length() + 1];
strcpy(orig2, _orig2.c_str());
*orig++;
*orig2++;
int a = atoi(orig);
int b = atoi(orig2);
delete[] orig;
delete[] orig2;
return 0;
}
运行上面的代码会因“ _CrtIsValidHeapPointer(block)”错误而崩溃。
如果我不进行迭代(* orig ++和* orig2 ++),则没有问题。
所以我的问题是,我该如何遍历指针,然后在完成对指针的操作后正确删除它们[]?
您没有删除分配的指针!
必须在new
返回的原始内存地址上调用delete
。 由于您执行过orig++
,因此无法delete
所指向的地址!
可以使用索引进行迭代,并使用数组订阅取消引用:
orig[i] = 'a';
这与执行此操作相同:
*(orig+i) = 'a';
或者,您可以将另一个指针指向相同的数据,然后对其进行修改。
char* pOrig = orig;
++pOrig;
你为什么写
*orig++; // why dereferencing?
仅仅++
本身就可以进行迭代。
避免使用原始指针。 您的代码可以更简单:
std::string orig = "[188 80% (1/2)O:152]";
std::string orig2 = "[999 99% (1/1)O:999]";
int a = atoi(orig.c_str() + 1);
int b = atoi(orig2.c_str() + 1);
您的错误是您尝试删除移位的指针而不是原始指针。 结果堆管理器出错,通常将分配的块信息放在分配的指针之前,从而导致堆损坏。
我如何遍历指针,然后在完成对指针的操作后正确删除[]?
创建指针的副本:
char* orig = new char[size];
char* i = orig;
*i++ = 'a';
delete orig;
也许更常见的习惯用法是取消对临时引用的引用:
for(int i = 0; i < size - 1; i++)
orig[i] = 'a';
我很想[使用
std::string
],但是我需要使用atoi(),它在std :: string上不起作用
你误会了。 atoi
可以与std::string
一起使用。 就像使用strcpy
一样,只需使用std::string::c_str()
即可。 绝对没有理由用new
分配一个内存块。
int testFunction()
{
std::string _orig = "[188 80% (1/2)O:152]";
int a = 0;
for (std::string::iterator it = _orig.begin(); it != _orig.end(); ++it)
{
if (isdigit((char)*it))
a = (atoi(it._Ptr));
}
return 0;
}
我知道了。 感谢所有帮助我得出这个结论的人。 坚持使用std :: string实际上是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.