由于超出界限地址的初始化导致的段错误

时间:2014-04-20 10:41:10

标签: c++ segmentation-fault

在我的项目中,我有一个结构Transaction,其中包含以下界面:

/**
 * Transaction interface
 */
struct Transaction
{
    Transaction () : signature(new char[20]), otherAcc(new char[20]), amount(0)
    {
    }

    Transaction (const Transaction &other)
    : signature(new char[20]),
    otherAcc(new char[20])
    {
        strcpy(signature, other.signature);
        strcpy(otherAcc, other.otherAcc);
    }

    Transaction& operator = (const Transaction &other)
    {
        if (&other != this)
        {
            // out with the old
            delete[] signature;
            delete[] otherAcc;

            // in with the new
            signature = new char[20];
            otherAcc = new char[20];
            strcpy(signature, other.signature);
            strcpy(otherAcc, other.otherAcc);
        }
        return *this;
    } 

    ~Transaction ()
    {
        delete[] signature;
        delete[] otherAcc;
    }

    char *signature;
    char *otherAcc;
    int amount;
};

我初始化链接列表的一个(公认的草率)实现,指向不同场合的事务:

/**
 * linked list interface
 */
template <class T>
struct node
{
    /**
     * constructs a node in of a linked list with the value provided
     * and a NULL next node
     */
    node (T initial_value) : value(initial_value), next(NULL), refs(1) {}

    /**
     * frees the memory
     * allocated in the linked list
     */
    void clear ()
    {
        clearList();
    }
    /**
     * frees all nodes as well as encapsulated values in the
     * linked list
     */
    void clearWithValue ()
    {
        if (this)
        {
            next->clearWithValue();
            if (value)
                delete value;
            delete this;
        }
    }

    T value;
    node<T> *next;
    unsigned refs;
    bool isFirst;

    private:
        /**
         * clears the rest of the list starting from the node at
         * which lear list was called
         */
        void clearList ()
        {
            if (this)
            {
                next->clearList();
                delete this;
            }
        }
    };

初始化看起来像这样,其中,accc和签名是const char *由函数传入:

    Transaction *new_trans = new Transaction;
    strcpy(new_trans->otherAcc, otherAcc);
    strcpy(new_trans->signature, signature);
    new_trans->amount = amount;
    data->transactions = new node<Transaction*>(new_trans);

我遇到了一个分段错误,我已经确定这是由链表中某个节点中的错误指针分配引起的。其中一个节点有value = { 0x343536373839 },由于它超出界限而无法访问,因此程序会出现段错误。这个问题是否与我未见到的记忆错误有关?我对这些东西很陌生并且调试这些内存错误可能是一个真正的痛苦,所以也欢迎一般的调试技巧。

修改 我运行它后,它在gdb中的段错误:

(gdb) bt
#3  0x00000000004015a0 in operator<< (os=..., acc=...) at tester.cpp:483

在我的程序中

os << walker->value->otherAcc;

其中walker的类型为node *

编辑:我添加了复制构造函数和赋值运算符,现在反映在Transaction接口中,但它没有解决段错误问题。

0 个答案:

没有答案