Memory leak problems while splitting a string in C -


im trying split string according following rules:

  1. words without "" around them should treated seperate strings
  2. anything wiht "" around should treated 1 string

however when run in valgrind invalid frees , invalid read size errors, if remove 2 frees memory leak. if point me in right direction appreciate it

the code calls split_string

    char *param[5];     for(i = 0;i < 5;i++) {             param[i] = null;     }     char* user = getenv("logname");     char tid[9];     char* instring = (char*) malloc(201);      /     while((printf("%s %s >",user,gettime(tid)))&&(instring             =fgets(instring,201,stdin)) != null) {             int paramsize = split_string(param, instring); 

the code tries free param

                for(i = 0;i < 5;i++) {                 if(param[i] != null) {                     free(param[i]);                     fprintf(stderr,"%d",i);                 }             } 

    int split_string(char** param, char* string) {     int paramplace = 0; //hvor vi er param     int tempplace = 0; //hvor temp vi er      char* temp = malloc(201);      int command = 0;      int message = 0;      for(; (*string != '\0') && (*string != 10) && paramplace < 4; string++) {             if((*string == ' ') && (message == 0)) {                     if(command == 1) {                         temp[tempplace] = '\0';                          param[paramplace++] = temp;                          tempplace = 0;                         command = 0;                     }             }             else {                     if(*string =='"') {                             if(message == 0) message = 1;                             else message = 0;                     }                     if(command == 0) {                             free(temp);                             temp = malloc(201);                     }                     command = 1;                     if(*string != '"') {                             temp[tempplace++] = *string;                     }             }     }     if(command == 1) {             temp[tempplace] = '\0';             param[paramplace++] = temp;     }     param[paramplace] = null;     free(temp);     return paramplace; } 

as far can see, want put split strings param array of pointers (presumably making caller responsible freeing them). in first branch of if statement in loop, assigning current temp buffer place. however, once start new string (when comnmand == 0, free space, rendering previous param entry pointer invalid.

only free each pointer once. wouldn't rule out other leaks in code: think can simplify state machine (and find other bugs result).


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -