c++ - 线路运算符(operator)新的段错误

标签 c++ pointers segmentation-fault new-operator delete-operator

函数 realloc_aray() 中完美的隐蔽错误。在 node * b = new node [size]; 行中,程序因段错误而崩溃。目前尚不清楚该计划为何落在 operator new 身上。我在 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];

关于c++ - 线路运算符(operator)新的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17673193/

相关文章:

c++ - Tokyo Cabinet : Segmentation fault at hdb->close()

go - 将字节数组传递给插件函数

C++:读取带分隔符的文件并存储在结构中

C - 字符串递归

c++ - 从 QMap 中删除一个指针?

C : Pointers and functions 2DArray

c++ - 如果允许堆栈分配的引用作为参数,如何进行通信?

c++ - 分区解决太慢

c++ - 如何在 Qt5 中使用带有模型/ View /委托(delegate)的自定义小部件?

python - 在 osx 上使用 numpy 的 lapack_lite 进行多处理的段错误,而不是 linux