I wrote a program in C that tokenizes an input string, and when the user enters "exit", it exits the program.
It tokenizes the string correctly, however, when I test my program with valgrind, I get some memory leaks. The only scenario when I don't get memory leaks is after compiling and then executing, I exit right away.
Here is the output with valgrind: Valgrind Memory Leaks
And here is my code for the program:
int main() {
/* Main Function Variables */
char *buf;
char *savecpy = NULL;
char *token;
size_t num_chars;
size_t bufsize = 2048;
int run = 1;
int tok_count = 0;
int cmp;
/* Allocate memory for the input buffer. */
buf = (char *) malloc(sizeof(char) * bufsize);
/*main run loop*/
while(run) {
/* Print >>> then get the input string */
printf(">>> ");
num_chars = getline(&buf, &bufsize, stdin);
cmp = strcmp(buf, "exit\n");
if (num_chars > 1) {
/* Tokenize the input string */
if (cmp != 0) {
/* Display each token */
savecpy = strdup(buf);
while((token = strtok_r(savecpy, " ", &savecpy))) {
printf("T%d: %s\n", tok_count, token);
tok_count++;
}
}
/* If the user entered <exit> then exit the loop */
else {
run = 0;
break;
}
}
tok_count = 0;
}
/*Free the allocated memory*/
free(buf);
return 1;
}
What may be the problem here that is causing the memory leaks in valgrind? I am freeing my memory for my input string, but I still get memory leaks.
savecpy
should be freed. As seen in the manual :
Memory for the new string is obtained with malloc(3), and can be freed with free(3).
savecpy
can not be freed after passing through strtok_r
third argument, as this function modifies the pointer. Rather pass something like this
char* ptr;
strtok_r(..,.., &ptr);
Then you can free savecpy
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.