c - c中的自由字符指针

标签 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;
}

这里可以不声明 command[],而是使用 *command 吗?我尝试使用它,但它抛出了异常。我们不需要释放像 command[] 这样声明的变量吗?如果是怎么办?

最佳答案

当你声明一个数组时:

char command[100];

编译器为其分配内存(在本例中为 100 个字符)并且 command 指向该内存的开头。您可以访问您分配的内存:

command[0]  = 'a';  // OK
command[99] = 'A';  // OK
command[100] = 'Z'; // Error: out of bounds

但是你不能改变command的值:

command = NULL;     // Compile-time error

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


当你声明一个指针时:

char *commandptr;

您只创建了一个指向 char 的变量,但它还没有指向任何东西。尝试在不初始化的情况下使用它是错误的:

commandptr[0] = 'A';   // Undefined behaviour; probably a segfault

您需要使用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
}

完成后释放它:

free(commandptr);

关于c - c中的自由字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656972/

相关文章:

c++ - 如何从 GNU/Linux 中的可执行文件导出特定符号

c++ - 使用 std::equal_range 查找出现在字符串 vector 中的前缀范围

c - 从 strtok 向其传递字符串数组后,execvp 返回错误 "No such file or directory"

c - 指向 C 中结构的指针

c++ - 如何返回列表中指针的值?

c - 函数内的函数

c++ - 将 vector 中的 wchar 字符串与其他指定的 wchar 字符串进行比较

c - 间隔定时器出现问题

c - 是否可以释放使用 calloc 分配的 char *"

你能解释一下以下 C 代码的输出吗?