I want to parse a string, and I use strsep
function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "Marco:Q:2F7PKC";
char *token1, *token2, *token3;
char *r = malloc(30);
strcpy(r, str);
token1 = strsep(&r, ":");
token2 = strsep(&r, ":");
token3 = strsep(&r, ":");
printf("tok1 = %s\n", token1);
printf("tok2 = %s\n", token2);
printf("tok3 = %s\n", token3);
free(r);
return 0;
}
The function do its job well, but If I launch valgrind, the allocated string char * r
does not freed correctly (definitely lost: 30 bytes in 1 blocks).
I'd like to know why and if there are alternative way to do the same thing, maybe without call strsep.
I call valgrind with valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./a.out