Free char pointer in c

46,382

Solution 1

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().

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.

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".

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.

Solution 2

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. 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 = NULL;     // Compile-time error

The memory will be automatically freed when command goes out of scope.


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:

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

You need to allocate the memory yourself using 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);

Solution 3

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

Share:
46,382
Sandeep Manne
Author by

Sandeep Manne

About Me

Updated on July 27, 2022

Comments

  • Sandeep Manne
    Sandeep Manne almost 2 years

    I am trying to find out filetypes 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 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?

  • Sandeep Manne
    Sandeep Manne over 13 years
    but can you explain me how to do it?
  • Bart van Ingen Schenau
    Bart van Ingen Schenau over 13 years
    You can, but then you must remember to call free in the calling function(s) to avoid a memory leak.
  • jamesdlin
    jamesdlin over 13 years
    For one thing, it probably would make sense to dynamically allocate a buffer based on the lengths of path and filename rather than silently allowing a buffer overflow. (C99 variable length arrays would solve this, though. Using snprintf instead of sprintf would be advisable too.)
  • KAction
    KAction almost 12 years
    Actually, stack array do not get freed, because it do not need to. To be totally honest, malloc and free are syscalls(well, wrappers to them), while stack array are not.