francesco torre
francesco torre

Reputation: 27

How do I use the free() function in c?

I'm using this function in my program:

static void free_envp(char **envp)
{
    free(envp);
}

I can't figure out how I should manage errors and which errors can occur, neither online nor in the man page.

Does anyone know what I should be aware of using it?

Upvotes: 1

Views: 941

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

The envp argument sounds like the environment pointer that is part of the main definition:

int main(int argc, char *argv[], char *envp[]);

Just as argv, you cannot deallocate envp. It is passed by the process environment.

(If your envp parameter has nothing to do with the envp argument of main, then you can ignore this part of my answer).

Note: you pass your function a pointer-to-a-pointer and then deallocate that. But probably the target of the pointer should be deallocated:

static void free_envp(char **envp)
{
    free(*envp);  // note the '*'
}

Upvotes: 1

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

The free function is called to free the memory which has been allocated on the heap. i.e. via malloc, calloc or realloc.

You should pass the same pointer that was returned by malloc to the free function. Since NULL can be returned by malloc in some cases, it is safe to pass NULL as argument to free, so that free(NULL) just does nothing.

Also, you should call the free function only once per malloc. Calling free on a pointer which has not been allocated or has already been freed is undefined behaviour.

For this reason, could be a good idea to set a pointer to NULL after is has been freed, if you are going to use it again.

int *p;
p = malloc(n * sizeof(int));  // n is size of the array
if (p == NULL)
{
    // Take appropriate action, e.g. exit the program.
}
....
.....

// After all use of the memory is over, if allocated properly before.
free(p);
p = NULL;

Upvotes: 3

Related Questions