c - Can't find the error in this code. (SIGSEGV) -
i writing method (c - language) should create new node linked list. crashes @ line after first if
(sigsegv signal)
i debugging method there more errors in subsequent lines, moment appreciate observations regarding particular line.
//create new tequivalencenode tequivalencenode* createnewequivalencenode(twordequivalence e){ //create new equivalence node tequivalencenode* node = null; node = (tequivalencenode*) malloc(sizeof(tequivalencenode)); //allocate memory both srcword , 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 @ line node->elem->srcword = source; //copy information destiny word in new node node->elem->dstword->languageid = e.dstword->languageid; node->elem->dstword->wordid = e.dstword->wordid; //allocate memory word , copy string 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 process source word node->elem->srcword->languageid = e.srcword->languageid; node->elem->srcword->wordid = e.srcword->wordid; //allocate memory word , copy string 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; }
this definition of twordinfo data type:
/* 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; };
and twordequivalence:
typedef struct { /* word in source language */ twordinfo* srcword; /* equivalent word in destination language */ twordinfo* dstword; } twordequivalence;
if((node != null)&&(destiny != null) && (source != null)){ node->elem->dstword = destiny; //crashes @ line
crashes because node->elem
not initialized. node->elem->dstword
dereferencing garbage pointer.
you want initialize new memory block:
node = (tequivalencenode*) malloc(sizeof(tequivalencenode)); node->elem = (twordequivalence*) malloc(sizeof(twordequivalence)); // ...
for record, simplify things (and wouldn't have had problem) if put twordequivalence
directly tequivalencenode
instead of using pointer:
struct tequivalencenode{ twordequivalence elem; tequivalencenode* next; };
Comments
Post a Comment