2012-01-09 104 views
2

當我將代碼(粘貼到下面)提交到在線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因爲這個問題有真正的大我輸入字符串)。所以我決定將字符串輸入存儲在一個字符數組中,這樣可以直接索引到特定的位置。

感謝任何幫助。

+0

你嘗試運行的valgrind? – PlasmaHH 2012-01-09 10:12:15

+1

'string'的''c_str'方法可以用來獲取'c-style'字符數組。沒有必要爲此編寫自己的字符串類。 – Naveen 2012-01-09 10:12:36

+0

隨着什麼輸入你會崩潰? – 2012-01-09 10:14:29

回答

3

有兩個問題,我可以看到:

cstr[test_cases-1] = new char[str_len]; // Not allocating space for terminating NULL. 

delete(cstr[test_cases-1]); // Incorrect delete, should be delete[] 
          // As already pointed out by mooware 

更改以下兩行:

cstr[test_cases-1] = new char[str_len + 1]; 

delete[] cstr[test_cases-1]; 
2

您正在使用array-new(「new char [str_len]」)來分配字符串,但標量刪除(「delete(cstr [test_cases-1])」)將其刪除。你應該總是匹配new和delete操作符,所以當你使用array-new時,也可以使用array-delete(「delete [] cstr [test_cases-1]」)。

1

你有兩個錯誤。一個在這裏:

cstr[test_cases-1] = new char[str_len]; 
    strcpy(cstr[test_cases-1],str.c_str()); 

你分配一個字節太少。這應該是new char[str_len+1],因爲strcpy複製終止符。

另一個是在這裏:

delete(cstr[test_cases-1]); 

你不能用new[]分配和使用delete解除分配。如果用new[]進行分配,則必須用delete[]取消分配。

相關問題