在此代码中找不到错误。 (SIGSEGV)

时间:2014-05-31 13:01:10

标签: c linked-list segmentation-fault

我正在编写这种方法(C语言),它应该为链表创建一个新节点。 它在第一个if(SIGSEGV信号)

之后的那一行崩溃

我正在调试方法,所以后续行中可能会有更多错误,但目前我会欣赏有关此特定行的任何观察。

//Create a new tEquivalenceNode
tEquivalenceNode* createNewEquivalenceNode(tWordEquivalence e){
    //create new equivalence node
    tEquivalenceNode* node = NULL;
    node = (tEquivalenceNode*) malloc(sizeof(tEquivalenceNode));
    //allocate memory for both srcWord and dstWord

    tWordInfo* destiny = NULL;
    tWordInfo* source = NULL;
    destiny = (tWordInfo*) malloc(sizeof(tWordInfo));
    source = (tWordInfo*) malloc(sizeof(tWordInfo));

    if((node != NULL)&&(destiny != NULL) && (source != NULL)){
        node->elem->dstWord = destiny; //Crashes at this line 
        node->elem->srcWord = source;
        //copy information to destiny word in the new Node
        node->elem->dstWord->languageID = e.dstWord->languageID;
        node->elem->dstWord->wordID = e.dstWord->wordID;
        //allocate memory for word and copy the string to the node
        node->elem->dstWord->word = (char*) malloc((strlen(e.dstWord->word) + 1)*sizeof(char));
        if(node->elem->dstWord->word != NULL){
            strcpy(node->elem->dstWord->word, e.dstWord->word);
        }

        //repeat the process for source word
        node->elem->srcWord->languageID = e.srcWord->languageID;
        node->elem->srcWord->wordID = e.srcWord->wordID;
        //allocate memory for word and copy the string to the node
        node->elem->srcWord->word = (char*) malloc((strlen(e.srcWord->word) + 1)*sizeof(char));
        if(node->elem->srcWord->word != NULL){
            strcpy(node->elem->srcWord->word, e.srcWord->word);
        }

        node->next = NULL;
    }
    return node;
}

这是tWordInfo数据类型的定义:

/* Dictionary Word */
typedef struct {
    int languageID;
    int wordID;
    char* word;
} tWordInfo;

tEquivalenceNode:

/* Equivalences list element */
typedef struct tEquivalenceNode tEquivalenceNode;
struct tEquivalenceNode{
    /* EX 1.1 */
    tWordEquivalence* elem; 
    tEquivalenceNode* next;
};

和tWordEquivalence:

typedef struct {
    /* Word in the source language */
    tWordInfo* srcWord;

    /* Equivalent word in destination language */
    tWordInfo* dstWord;

} tWordEquivalence;

2 个答案:

答案 0 :(得分:0)

if((node != NULL)&&(destiny != NULL) && (source != NULL)){
    node->elem->dstWord = destiny; //Crashes at this line 

崩溃,因为node->elem未初始化。因此node->elem->dstWord将垃圾解除引用作为指针。

您可能希望将其初始化为新的内存块:

node = (tEquivalenceNode*) malloc(sizeof(tEquivalenceNode));
node->elem = (tWordEquivalence*) malloc(sizeof(tWordEquivalence));
// ...

对于记录,如果您将tWordEquivalence直接放入tEquivalenceNode而不是使用指针,它会简化事情(并且您不会遇到此问题):

struct tEquivalenceNode{
    tWordEquivalence elem; 
    tEquivalenceNode* next;
};

答案 1 :(得分:0)

您从未初始化node->elem

tEquivalenceNode* node = malloc(sizeof(tEquivalenceNode));

//allocate memory for elem
node->elem = malloc(sizeof(*(node->elem)));