c - How to fix console return of malloc(): memory corruption (fast) -


when ran program, console output showed following: malloc(): memory corruption (fast) , followed seemed address in memory. have narrowed down few functions, feel free memory allocate properly.

the following function takes string representing file name.

void readandprocessfile(char* filename){      file *fileptr;     char* word = malloc(32*sizeof(char));      fileptr = fopen(filename, "r");      while(fscanf(fileptr,"%s",word) != eof){         processword(word);     }      fclose(fileptr);     free(word); } 

this function takes word, removes non-alphabetic characters , changes letters uppercase.

void processword(char* text){     char* processedword;     processedword = trimandcaps(text);      if(processedword != null && processedword[0] != '\0'){         addword(processedword);     }     free(processedword); } 

here's trim , cap function

char* trimandcaps(char* text) {     int = 0;     int j = 0;     char currentchar;     char* rv = malloc(sizeof(text));      while ((currentchar = text[i++]) != '\0')     {         if (isalpha(currentchar))         {             rv[j++] = toupper(currentchar);         }     }     rv[j] = '\0';      return rv; } 

and measure here's addword function

void addword(char* word) {     // check if word in list     struct worddata* currentword = findword(word);      // word in list     if(currentword != null)     {         incrementcount(currentword);     }     // word not in list     else     {         currentword = malloc(sizeof(struct worddata));         currentword->count = 1;         strcpy(currentword->word, word);         ll_add(wordlist, currentword, sizeof(struct worddata));         free(currentword);     } } 

as can see, instances manually allocate memory, free afterwards. program works when there smaller amount of words, not larger. thought process leads me believe there sort of leak, when have few enough words point can run it, run following code:

// following code print out final dynamic memory used struct mallinfo veryend = mallinfo(); fprintf(stderr, "final dynamic memory used : %d\n", veryend.uordblks); 

and shows 0 every time memory used. else can cause this? direction or fixes appreciated.

the following line doesn't hoping to:

char* rv = malloc(sizeof(text)); 

it allocates 4 or8 bytes or memory depending on size of pointers on platform.

you need:

char* rv = malloc(strlen(text) + 1); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -