Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free char pointer in c

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?

like image 891
Sandeep Manne Avatar asked Sep 07 '10 08:09

Sandeep Manne


People also ask

What is a char pointer in C?

A pointer may be a special memory location that's capable of holding the address of another memory cell. So a personality pointer may be a pointer that will point to any location holding character only. Character array is employed to store characters in Contiguous Memory Location.

Should char pointers be freed?

Every pointer which is allocated any memory using new/malloc has to be freed using delete/free respectively. If not freed, it's called memory leaking. Same applies for Char pointer also.

What happens when you free a pointer in C?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.

Is char * a pointer or a string?

The 'char *' doesn't magically create a string, it really is just a pointer (to a single character).


2 Answers

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);
like image 150
Nefrubyr Avatar answered Oct 05 '22 10:10

Nefrubyr


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.

like image 28
Bart van Ingen Schenau Avatar answered Oct 05 '22 12:10

Bart van Ingen Schenau