简体   繁体   中英

do i need to free a malloc'ed array which i passed as argument to execve()?

I created a simple shell program that
_displays a prompt
_receives user input using readline()
_splits the input into words based on where spaces are found in the input string
_the words are then put in an array (which is MALLOC'ed) ;
_fork() is used to create a child process
_i then pass this array to call a program from the child process using execve()
execve(myarray[0], myarray, env); and the current process waits for it.

MY QUESTION IS: Do i need to free the MALLOC'ed memory of myarray ?
Here is a part of the code

  child_pid = fork();
 42                 if (child_pid == -1)
 43                 {
 44                         perror(argv[0]);
 45                         free(linebuffer);
 46                         return (2);
 47                 }
 48
 49                 if (child_pid == 0)
 50                 {
 51                         /*strsplit() returns MALLOC'd array*/
 52                         splitted_str = _strsplit(linebuffer, ' ');
 53
 54                         if (execve(splitted_str[0], splitted_str, env) == -1)
 55                         {
 56                                 perror(argv[0]);
 57                                 
             /*Function that frees a NULL terminated array*/  
free_array(splitted_str);
 58                                 free(linebuffer);
 59
 60                                 return (2);
 61                         }
 62                 }
 63                 else
 64                 {
 65                         wait(NULL);
 66                 }

Do i need to free the MALLOC'ed memory of myarray?

You do not need to free it in the process that calls execve() . On success, that function replaces the entire process image with a new one, so there is nothing left to free and no way to free it. For the purposes of the new program, the the second argument to main() and the strings in that array are not dynamically allocated and cannot be freed. On execve() failure, on the other hand, the calling process ought to terminate immediately, and doing so is sufficient to serve any need to free allocated memory in that process.

However, if you perform the allocation before fork ing, which it sounds like you do, then you probably do need to free the memory in the process that does not call execve() . You might not bother if that one were going to terminate soon anyway, but if it's going to continue running indefinitely, processing an indefinite number of additional commands, then you should free the memory when you are done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM