[英]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.