检测到glibc - 双重免费或腐败

时间:2012-01-09 10:07:56

标签: c++ free glibc

当我将代码(粘贴在下面)提交给在线gcc编译器时,我收到以下错误消息。

  

* glibc检测到 / run-1326102706-2046832693 /解决方案:双重免费或损坏(!prev):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函数非常慢(特别是因为这个问题确实有很大的输入字符串)。所以我决定将字符串输入存储在字符数组中,以便可以直接索引到特定位置。

感谢任何帮助。

3 个答案:

答案 0 :(得分: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];

答案 1 :(得分:2)

您正在使用array-new(&#34; new char [str_len]&#34;)来分配字符串,但是标量删除(&#34;删除(cstr [test_cases-1])&#34 ;)删除它们。你应该总是匹配new-和delete-operator,所以当你使用array-new时,也要使用array-delete(&#34; delete [] cstr [test_cases-1]&#34;)。

答案 2 :(得分: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[]解除分配。