Reputation: 675
Shouldn't I free s_ptr after every call to strtok_r() (extract tokens from strings)?
static void get_uevent_info(struct media_device_entry *md_ptr, char *dname)
{
FILE *fd;
char file[PATH_MAX], *name, *p;
char s[1024];
char *s_ptr;
snprintf(file, PATH_MAX, "%s/%s/uevent", dname, md_ptr->node);
fd = fopen(file, "r");
if (!fd)
return;
while (fgets(s, sizeof(s), fd)) {
p = strtok_r(s, "=", &s_ptr);
if (!p)
continue;
name = p;
p = strtok_r(NULL, "\n", &s_ptr);
if (!p)
continue;
if (!strcmp(name, "MAJOR"))
md_ptr->major = atol(p);
else if (!strcmp(name, "MINOR"))
md_ptr->minor = atol(p);
}
fclose(fd);
}
I never used that function, so maybe I'm wrong.
Best regards.
Upvotes: 3
Views: 2178
Reputation: 3097
s_ptr
shouldn't be freed as it is not allocated by malloc
or calloc
or realloc
. Man page says as,
The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string
.
That said, strtok_r
does not allocate memory. So just sending an address of pointer to char ie.,char **
is enough and nothing is needed after returning. It doesn't matter even when the char *
is not initialized, but still initializing the pointers to NULL
is a good practice to avoid nightmares..
Upvotes: 5