检测到glibc-两次释放或损坏 [英] glibc detected - double free or corruption

查看:82
本文介绍了检测到glibc-两次释放或损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将代码(粘贴到下面)提交给在线gcc编译器时,出现以下错误消息.

I get the following error messages when I submit the code (pasted below) to an online gcc compiler.

*检测到glibc /run-1326102706-2046832693/solution:两次释放或损坏(!prev):0x091901a8 * * =======

* glibc detected /run-1326102706-2046832693/solution: double free or corruption (!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函数的运行速度非常慢(特别是因为此问题的输入字符串很大).因此,我决定将输入的字符串存储在字符数组中,以便可以直接索引到特定位置.

As mentioned in the code itself, I initially used std::string, but found that the std::string.at function was quite slow (esepcially since this problem has really large input strings). So I decided to store the string input in a character array, so that direct indexing to a particular position would be possible.

感谢任何帮助.

推荐答案

我可以看到两个问题:

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];

这篇关于检测到glibc-两次释放或损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆