简体   繁体   中英

Shouldn't I free char when using strtok_r

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.

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..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM