线路运营商新出现分段故障

Segmentation fault on the line operator new

本文关键字:故障 分段 新出现 运营商 线路      更新时间:2023-10-16

函数realloc_aray()中的完全模糊错误。在线路中,node * b = new node [size];程序因分段故障而崩溃。目前尚不清楚为什么这个程序会落到新操作员的头上。我在GDB中调试了它。变量size = 9的值,也就是说原因不是内存不足?

void compress::compresser::compress_string(const std::string& s, std::string& t)
{
    std::vector<std::string> r;
    tokenize(s, r);
    int l = r.size() - 1;
    node tt[l][l];    
    node* a = new node[l];
    for(int i = 0; i < l; ++i)
    {
         node* rr = m_tree->get_new_node(atoi(r[i].c_str()));
         a[i] = *rr;
    }
    int m = dec_to_bin(l); 
    node* b = get_xor_array(a, l);
//  delete [] a;
    for(int i = 0; i < m; ++i )
    {
        for(int j = 0; j < l; j+=2)
        {
            node* n = m_tree->get_new_xor_node(&b[j], &b[j + 1]);
            tt[i][j] = *n;
            delete n;               
        }
        l = l/2; 
//      delete [] b;
        b = get_xor_array(tt[i], l);            
    }
}
compress::node* compress::compresser::get_xor_array(const node* const a, int  size)
{
    node* b = 0;
    b = realloc_array(a, size);
    return b;
}
compress::node* compress::compresser::realloc_array(const node* const a, int size)
{
    int i = 0;
    node* b = new node[size]; // in this line program crashes with segmentation fault
    for(i = 0; i < size; ++i)
    {
        b[i] = a[i];
    }
    b[size] = 0;
    return b;
}

C++数组是基于零的,因此

node* b = new node[size];

分配一个具有索引[0..size-1]的数组。行

b[size] = 0;

写入超过已分配内存的末尾。这会产生未定义的后果,包括重写程序其他部分使用的内存。

如果要为size node实例加上NULL终止符分配空间,请使用

node* b = new node[size+1];