C语言 c中的免费字符指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3656972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:23:56  来源:igfitidea点击:

Free char pointer in c

cstringpointerschar

提问by Sandeep Manne

I am trying to find out filetypes using c code, here is the code

我正在尝试使用 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;
}

here instead of declaring command[], can I use *command? I tried to use it, but it throwed an exception. we dont need to free up variables declared like command[]? if yes how?

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

回答by Nefrubyr

When you declare an array:

当你声明一个数组时:

char command[100];

the compiler allocates the memory for it (100 chars in this case) and commandpoints to the start of that memory. You can access the memory you've allocated:

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

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

but you cannot change the value of command:

但您不能更改 的值command

command = NULL;     // Compile-time error

The memory will be automatically freed when commandgoes out of scope.

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



When you declare a pointer:

当你声明一个指针时:

char *commandptr;

you only create a single variable for pointing to chars, but it doesn't point to anything yet. Trying to use it without initialising it is an error:

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

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

You need to allocate the memory yourself using malloc:

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

and free it when you've finished with it:

完成后释放它:

free(commandptr);

回答by Bart van Ingen Schenau

You can use char *command;, but then, you must allocate some memory for commandto refer to with a call to malloc()and when you are done ith that memory, it has to be freed again with a call to free().

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

As you can see, that is a lot more work than using a fixed-size array (as you do now), but it can be made a lot safer as well, because you could create a buffer of exactly the right size, instead of hoping that the total length of the command won't exceed 100 characters.

如您所见,这比使用固定大小的数组(就像您现在所做的那样)要做的工作要多得多,但它也可以变得更安全,因为您可以创建一个大小完全正确的缓冲区,而不是希望命令的总长度不会超过 100 个字符。

Aside from that, your code has a problem: The filetypepointer that the function returns points to a location within the array file_details, but that array will be cleaned up by the compiler when executing the returnstatement, so the pointer that gets returned by the function refers to some memory that is marked as "free to be used for other purposes".

除此之外,您的代码有一个问题:filetype函数返回的指针指向数组中的某个位置file_details,但是该数组在执行return语句时会被编译器清理,因此函数返回的指针是指一些标记为“可自由用于其他目的”的内存。

If it is not a problem that the result of get_file_typeis only valid for one file at a time, you can declare the file_detailsarray as static, so that it will be preserved across calls to the function.

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

回答by Alexander Rafferty

Why would you change it? For temporary buffers, people usually declare the arrays with [] so they don't have to worry about garbage disposal.

你为什么要改变它?对于临时缓冲区,人们通常用 [] 声明数组,这样他们就不必担心垃圾处理。