Im trying to split a string according to the following rules:
- words without “” around them should be treated as seperate strings
- anything wiht “” around it should be treated as one string
However when i run it in valgrind i get invalid frees and invalid read size errors, but if i remove the two frees i get a memory leak. If anyone could point me in the right direction i would appreciate it
The code that 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 that tries to 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 i param
int tempplace = 0; //hvor i 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 as I can see, you want to put the split strings into
paramas an array of pointers (presumably making the caller responsible for freeing them). In the first branch of the if statement in your loop, you do so by assigning the currenttempbuffer to that place. However, once you start a new string (whencomnmand == 0, you free that space, rendering the previousparamentry pointer invalid.Only free each pointer once. I wouldn’t rule out other leaks in this code: I think you can simplify your state machine (and probably find other bugs as a result).