Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory created by malloc after using execvp?

Tags:

c

linux

exec

In my C program, I create a child process and in it, it parses a string and created a pointer array (using malloc()) for the use of passing it in execvp() command.

But the problem is, how do you free the memory that the child created? execvp() runs the new task and may or may not return. If it doesn't return, then it was successful and the child dies (and I can't really use the free() command). If it failed then it returned, then it continues doing the next lines of code, is this the only chance to free the memory?

like image 515
omega Avatar asked Jan 24 '13 02:01

omega


1 Answers

You don't need to. Specifically, if you allocate memory in a process before an exec()-type routine (e.g., execvp() in your case) is called, all of the memory associated with the original executable is released. It's a similar situation to a process exiting (and having all its resources released), and a new process being started with a clean slate.

like image 177
radical7 Avatar answered Nov 11 '22 07:11

radical7