想要在strtok之后释放我的指针令牌

ror*_*oro 4 c free char strtok

我已经提取了我的代码的"含义"部分(并且还替换了一些行来简化它).

我有2个动态指针,一个用于当前行(从文件中提取),另一个用于当前令牌.在这个问题之后,在处理完整的字符串之前,自由/删除strtok_r指针? 我写了这个:

int main(void) {
    int n = 455;  
    char *tok2, *freetok2;
    char *line, *freeline;

    line = freeline = malloc(n*sizeof(*line));
    tok2 = freetok2 = malloc(n*sizeof(*tok2));

    /* content of the file) */
    const char* file_reading =  "coucou/gniagnia/puet/";

    /* reading from the file */
    strcpy(line, file_reading);

    strtok(line, "/");
    /* get the second token of the line */
    tok2 = strtok(NULL, "/");

    fprintf(stdout, "%s \n", tok2); // print gniagnia
    fprintf(stdout, "%s \n", line); // print coucou

    /* free error */
    //free(tok2);

    /* worked, but maybe don't free "everything ?" */
    //free(line);

    free(freetok2);
    free(freeline);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但最后,我不确定什么是正确的,我发现这个解决方案不那么优雅(因为使用了2个"保存变量").

那是对的吗 ?有没有办法改善它?谢谢

编辑:更改了我的代码,(它将处理文件的所有行)

include <unistd.h>
include <stdlib.h>

int main(void) {
    char *tok2; 
    char *line; 

    /* content of the file) */
    const char* file_reading =  "coucou/gniagnia/puet/";
    const char* file_reading2 =  "blabla/dadada/";

    /* reading from the file */
    line = strdup(file_reading);

    strtok(line, "/");
    /* get the second token of the line */
    tok2 = strtok(NULL, "/");

    printf("%s \n", tok2);
    printf("%s \n", line);

    /* reading from the file */
    line = strdup(file_reading2);

    strtok(line, "/");
    /* get the second token of the line */
    tok2 = strtok(NULL, "/");

    printf("%s \n", tok2);
    printf("%s \n", line);

    free(line);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 5

你实际上并没有使用指向的内存freetok2,你不需要malloc任何东西,因此你不需要freetok2变量.

在代码中说free(line)free(freeline) 相同,所以你根本不需要它freeline.

另一个问题是:malloc(n*sizeof(*line));.你可能会说:malloc(n);因为sizeof(char)总是1.但最重要的是:

line = malloc(strlen(file_reading) + 1);
strcpy(line, file_reading);
Run Code Online (Sandbox Code Playgroud)