c - Replacing Tab(s) with a Space - Memory Issues (free invalid next size fast) -


i trying pass string tab(s) in function, , have function replace each tab, or repeating tabs space. problem having regarding memory issues. here code:

void converttoonespace(char *dst, char *src) {     int i, j, first_tab = 1;      for(i = 0, j = 0; src[i] != '\0'; i++) {         if (src[i] == '\t' && first_tab == 0) continue;         if (src[i] == '\t' && first_tab == 1) {             first_tab = 0;             dst[j] = ' ';         } else {             first_tab = 1;             dst[j] = src[j];         }         j++;     }     dst[j] = '\0'; }  int printcomment(char *desc) {     char astring[4096];     char *result = null;      strcpy(astring, desc);     result = strtok(astring, "\n");     while(result != null) {         result_notabs = (char *)malloc(sizeof(char) * strlen(result)));         converttoonespace(result_notabs, result);         printf("%s\n", result_notabs);         /* code operates on result_notabs, splitting multiple sub             strings of shorter length. code tested working              before implementing , utilizing converttoonespace */         free(result_notabs);     }     return 0; } 

i run printcomment() on multiple strings (hundreds), random print statements verify working should. does, until appears random string (nothing special can tell) , following error:

     free(): invalid next size (fast)  

i assuming memory related, because when valgrind (with memcheck), works perfectly. can spot error? assuming isnt in other code have left out (as comment says, working before implementing this).

thanks!

the line

result_notabs = (char *)malloc(sizeof(char) * strlen(result))); 

should be

result_notabs = malloc(strlen(result) + 1); 

to leave space null terminator @ end of result. without this, converttoonespace writes beyond end of result_notabs. has undefined consequences include writing memory used other parts of program.

note made couple of other changes line

  • removed cast return of malloc. isn't required in c , can mask bugs
  • removed use of sizeof(char) since guaranteed 1

you should note comment elchonon edelson.

char *astring[4096]; 

declares array of 4096 char pointers. code needs array of chars instead

char astring[4096]; 

(this won't have caused problem worth getting habit of using correct type strings)


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -