c中的自由字符指针

San*_*nne 5 c string pointers char

我试图找出使用c代码的文件类型,这里是代码

char *get_file_type(char *path, char *filename)
{
    FILE *fp;
    char command[100];
    char file_details[100];
    char *filetype;

    sprintf(command, "file -i %s%s", path, filename);
    fp = popen(command, "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }
    while (fgets(file_details,  sizeof(file_details)-1, fp) != NULL) {
         filetype = (strtok(strstr(file_details, " "), ";"));
    }

    pclose(fp);
    return filetype;
}
Run Code Online (Sandbox Code Playgroud)

这里不是声明命令[],我可以使用*命令吗?我试图使用它,但它抛出异常.我们不需要释放像command []声明的变量吗?如果有,怎么样?

Nef*_*byr 11

声明数组时:

char command[100];
Run Code Online (Sandbox Code Playgroud)

编译器为它分配内存(在这种情况下为100个字符)并command指向该内存的开头.您可以访问已分配的内存:

command[0]  = 'a';  // OK
command[99] = 'A';  // OK
command[100] = 'Z'; // Error: out of bounds
Run Code Online (Sandbox Code Playgroud)

但你无法改变以下值command:

command = NULL;     // Compile-time error
Run Code Online (Sandbox Code Playgroud)

command超出范围时,内存将自动释放.


声明指针时:

char *commandptr;
Run Code Online (Sandbox Code Playgroud)

你只创建一个指向chars的变量,但它还没有指向任何东西.尝试使用它而不初始化它是一个错误:

commandptr[0] = 'A';   // Undefined behaviour; probably a segfault
Run Code Online (Sandbox Code Playgroud)

您需要使用malloc以下方式自行分配内存:

commandptr = malloc(100);
if (commandptr) {
    // Always check that the return value of malloc() is not NULL
    commandptr[0] = 'A';  // Now you can use the allocated memory
}
Run Code Online (Sandbox Code Playgroud)

当你完成它时释放它:

free(commandptr);
Run Code Online (Sandbox Code Playgroud)


Bar*_*nau 5

您可以使用char *command;,但是,您必须分配一些内存command以通过调用来引用malloc(),当您完成该内存时,必须通过调用再次释放它free().

正如你所看到的,是比使用固定大小的数组(因为你现在做的)很多工作,但它可以做了很多安全为好,因为你可以创建一个完全正确的大小的缓冲区,而不是希望命令的总长度不超过100个字符.

除此之外,你的代码有一个问题:filetype该函数返回指向数组中的位置指针file_details,而是数组由编译器执行时被清理return的语句,这样得到由该函数返回的指针指一些标记为"可以自由用于其他目的"的内存.

如果结果get_file_type仅对一个文件一次有效不成问题,则可以将file_details数组声明为static,以便在调用函数时保留该数组.