即使在更改代码时也会出现分段错误

时间:2013-03-19 05:22:09

标签: c segmentation-fault

我一直在研究哈希表。我一直遇到分段错误。我一直在尝试调试它,但它总是指向addOrder有分段错误。

我哪里错了?还有什么其他方法可以实现我的代码来检查任何极端情况?

struct order 
{
    int id;
    char side;
    int quantity;
    double price;
};

struct onode 
{
    struct order* data;
    struct onode* next;
    struct onode* prev;
};

/*
 * Create a new instance of struct hashStorage and return it. It sets the size of the
 * table to be of length "size" which will be the number of the entries in the hash. It takes also an
 * argument to specify the format of the order printed to an output stream. If myHash parameter
 * is NULL then this means that the hash should be a linked list. When myHash is NULL the size
 * parameter should be ignored.
 */

struct hashStorage* createHash(int size, int (*myHash)(int),void(*printOrder)(struct order *, FILE *))
{
    struct hashStorage* hashList = (struct hashStorage*) malloc(sizeof(struct hashStorage));

    if(myHash == NULL)
    {
        hashList->size = 1;
        hashList->table = (struct onode**) calloc(1, sizeof(struct onode*));
    }

    if(myHash != NULL)
    {
        hashList->table = (struct onode**) calloc(size, sizeof(struct onode*));
        hashList->size = size;
    }
    hashList->funcHash = myHash;
    hashList->printItem = printOrder;        
    return hashList;
}

/*
 * Add an order to the hash structure. Remember that you should copy the data before
 * adding it to the hash as data can be modified (hint: look at newNode in list).  
 * It returns the new onode.              
 */
struct onode* addOrder(struct hashStorage* hash, struct order* data)
{
    int addIndex; 
    struct onode* dataList = newNode(data);
    addIndex = hash -> funcHash(getOrderId(data));
    pushNode(&(hash->table[addIndex]), dataList);
    return dataList;                            
}

1 个答案:

答案 0 :(得分:0)

我建议你看看来自glib库的GHashTable代码,它有一个很好的注释代码,你将能够理解。

希望它有所帮助!