void myFree(void * p, char * fn, int ln){ memEntry *ptr; memEntry *before; //memEntry for the previous block memEntry *after; //memEntry for the next block if(sl == NULL) { printf(KRED "Error: No malloced/calloced memory in the list. Failed to free.\n" KNRM); return; } if(SLFind(sl, p) == NULL) { printf(KRED "Error: This memory pointer was never malloced/calloced in the list. Failed to free.\n" KNRM); return; } ptr = (memEntry *)((char *)p - sizeof(memEntry)); if((before = ptr->prev) != 0 && before->isFree){ before->size += sizeof(memEntry) + ptr->size; // Combining with the previous memEntry free block before->next = ptr->next; ptr->isFree = 1; before->next = ptr->next; if(ptr->next != 0){ ptr->next->prev = before; } SLRemove(sl, p); } else { if (ptr->isFree == 0) { SLRemove(sl, p); ptr->isFree = 1; before = ptr; printf(KGRN "Freed block 0x%x\n" KNRM, p); } else { printf(KRED "Error: Attempted to double free a pointer. Failed to free.\n" KNRM); } } if((after = ptr->next) != 0 && after->isFree){ before->size += sizeof(memEntry) + after->size; // // Merging with the next memEntry free block before->next = after->next; before->isFree = 1; if(after->next != 0) { after->next->prev = before; } SLRemove(sl, p); } }
void add_word(char *filename, char *wordToAdd, char *tokenString) { FileWithCount file; file = (FileWithCount) malloc( sizeof(FileWithCount) ); file->filename = (char *) malloc( BUFSIZ+1 ); snprintf(file->filename, BUFSIZ, "%s", filename); file->count = 1; printf("Filename after file %s and should be %s\n",file->filename,filename); /*Find if word exists*/ WordNode wordToFind = (WordNode) malloc(sizeof(WordNode)); wordToFind->word = (char *) malloc (BUFSIZ+1); snprintf(wordToFind->word, BUFSIZ, "%s", wordToAdd); WordNode isWordThere; isWordThere = (WordNode) SLFind(wordList, wordToFind); if (isWordThere != NULL) { /*Word already exists*/ printf("WORD EXISTS: %s\n", wordToAdd); SortedListIteratorPtr iter; iter = SLCreateIterator(isWordThere->files); void *obj = NULL; while ((obj = SLNextItem(iter))) { FileWithCount objFile; objFile = obj; if (compareFilesWithCount(objFile, file) == 0) { /*Filename present, just increase count and break*/ objFile->count++; break; } } SLDestroyIterator(iter); if(obj == NULL) { /*File not found, insert it into list*/ printf("Filename before slinsert %s\n",file->filename); SLInsert(isWordThere->files, file); printf("Inserted file %s into word %s\n",file->filename,isWordThere->word); printf("Filename actually %s\n",filename); free (wordToFind->word); free (wordToFind); } else { fprintf(stderr, "ERROR: Add Word\n"); free (file->filename); free (file); free (wordToFind->word); free (wordToFind); } return; } else { /*Word doesn't exist yet*/ wordToFind->files = SLCreate(compareFilesWithCount); /* printf("The word of the day is %s\n", w->word); */ /*Insert file path into word*/ SLInsert(wordToFind->files, file); /*Insert word into word list*/ SLInsert(wordList, wordToFind); return; } }