简体   繁体   English

c中的自由字符指针

[英]Free char pointer in c

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[]? 我们不需要释放像command []声明的变量吗? if yes how? 如果有,怎么样?

When you declare an array: 声明数组时:

char command[100];

the compiler allocates the memory for it (100 chars in this case) and command points to the start of that memory. 编译器为它分配内存(在这种情况下为100个字符), command指向该内存的起始位置。 You can access the memory you've allocated: 您可以访问已分配的内存:

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 command goes out of scope. command超出范围时,将自动释放内存。


When you declare a pointer: 声明指针时:

char *commandptr;

you only create a single variable for pointing to char s, but it doesn't point to anything yet. 你只创建一个指向char的变量,但它还没有指向任何东西。 Trying to use it without initialising it is an error: 尝试使用它而不初始化它是一个错误:

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);

You can use char *command; 你可以使用char *command; , but then, you must allocate some memory for command to 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() . 但是,你必须为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 filetype pointer 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 return statement, 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语句时编译器将清理该数组,因此return的指针由function是指一些标记为“可以自由地用于其他目的”的内存。

If it is not a problem that the result of get_file_type is only valid for one file at a time, you can declare the file_details array as static , so that it will be preserved across calls to the function. 如果get_file_type的结果一次只对一个文件有效并不是问题,则可以将file_details数组声明为static ,以便在调用该函数时保留它。

Why would you change it? 你为什么要改变它? For temporary buffers, people usually declare the arrays with [] so they don't have to worry about garbage disposal. 对于临时缓冲区,人们通常使用[]声明数组,因此他们不必担心垃圾处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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