當我將代碼(粘貼到下面)提交到在線gcc編譯器時,出現以下錯誤消息。glibc detected - double free or corruption
* glibc的檢測 /運行1326102706-2046832693 /解決方案:雙重釋放或腐敗(上一個!):0x091901a8 * * =======
的代碼如下:
# include <iostream>
# include <string>
# include <list>
# include <cstring>
using namespace std;
int main()
{
int test_cases, i, score, str_len;
string str;
char first_char, current_char;
list <int> strlist;
list <int> :: iterator it;
cin>>test_cases;
char *cstr[test_cases]; //Creating an array of cstr pointers (test_cases number of pointers)
while(test_cases > 0)
{
cin>>str;
first_char = str.at(0);
str_len = str.length();
score = str_len;
strlist.clear();
cstr[test_cases-1] = new char[str_len];
strcpy(cstr[test_cases-1],str.c_str()); //copying the input str into cstr. This is done to minimize the complexity of std::string's at function.
for(i=1;i<str_len; i++)
{
current_char = *(cstr[test_cases-1]+i);
if (current_char == first_char)
{
score++; strlist.push_front(1);
it = strlist.begin();
if (it != strlist.end())
it++;
}
while (!strlist.empty() && it != strlist.end())
{
if (current_char == *(cstr[test_cases-1] + *(it)))
{
(*it)++;it++;score++;
}
else
it = strlist.erase(it);
}
if (!strlist.empty())
it = strlist.begin();
}
cout<<score<<endl;
delete(cstr[test_cases-1]);
test_cases--;
}
return 0;
}
正如代碼本身所提到的,我最初使用的std :: string,但發現的std :: string.at功能是相當慢(esepcially因爲這個問題有真正的大我輸入字符串)。所以我決定將字符串輸入存儲在一個字符數組中,這樣可以直接索引到特定的位置。
感謝任何幫助。
你嘗試運行的valgrind? – PlasmaHH 2012-01-09 10:12:15
'string'的''c_str'方法可以用來獲取'c-style'字符數組。沒有必要爲此編寫自己的字符串類。 – Naveen 2012-01-09 10:12:36
隨着什麼輸入你會崩潰? – 2012-01-09 10:14:29