gpt4 book ai didi

找不到这段代码的错误。 (SIGSEGV)

转载 作者:行者123 更新时间:2023-11-30 19:46:24 26 4
gpt4 key购买 nike

我正在编写这个方法(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;

最佳答案

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;
};

关于找不到这段代码的错误。 (SIGSEGV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23970378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com