【发布时间】:2014-05-31 13:01:09
【问题描述】:
我正在编写这个方法(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;
【问题讨论】:
-
node->elem可能为 null 或未初始化。 -
题外话:不要强制转换malloc的结果:stackoverflow.com/questions/605845/…
-
是的,它没有初始化。谢谢!
-
感谢@Barmar 提供链接。
标签: c linked-list segmentation-fault