Free char pointer to c

I am trying to find file types using c code, here is the code

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 the command [], can I use the * command? I tried to use it, but he threw an exception. do we need to free variables declared as command []? if so, how?

+5
source share
3 answers

You can use it char *command;, but then you must allocate some memory commandto call the call malloc(), and when you are done with this memory, it should be freed by the call again before free().

, , ( ), , , , , 100 .

, : filetype, file_details, return, , , , " ".

, get_file_type , file_details static, .

+5

:

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 s, . - :

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

Why do you need to change this? For temporary buffers, people usually declare arrays with [], so they don’t have to worry about garbage disposal.

+1
source

All Articles