c - Freeing memory after passing value causing EXC_BAD_ACCESS -


when free normalizedword in foo after passing addelement segfault when trying strcmp key. without freeing, there's no issue, other gigantic memory leak. idea might going on here?

foo(char* word) {     char* normalizedword = (char*)(malloc(strlen(word) + 1);     strcpy(normalizedword, word);      normalize(normalizedword);     int result = addelement(dict->hashtable, normalizedword);      free(normalizedword);     return result; }  addelement(hashtable *hashtable, const char *key) {     if (0 == hashtable->elements[hashindex])     {         // add new element         hashtable->elements[hashindex] = createelement(key);     }     else     {         // search existing or add new element         element* current = hashtable->elements[hashindex];          /* error here... */         while (0 != strcmp(current->key, key))         {             if (null == current->next)             {                 current->next = createelement(key);                 break;             }             else             {                 current = current->next;             }         }     }      return 0; }  element* createelement(const char* key) {     element* element;      if (null == (element = malloc(sizeof(element))))     {         return null;     }      element->key = (char*) malloc(strlen(key) + 1);     strcpy(element->key, key);      return element; } 

one problem see element->next not initialized while creating element. clear next not static member, hence when first element added, next value contain garbage. , because of this, current assigned garbage value following section of code:

else {     current = current->next; } 

which caused out of segment memory access in strcmp();

adding element->next=null; in createelement() function may fix segmentation fault.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -