1

I have this code:

  std::vector<std::string> args_ {"./test_script.sh"};
  pid_t child_pid = fork();

  switch (child_pid)
  {
  case 0:
  {
    // Child process
    char ** args = new char*[args_.size() + 1];
    for(size_t i = 0; i < args_.size(); ++i){
      args[i] = new char[args_[i].size() + 1];
      strcpy(args[i], args_[i].c_str());
    }
    args[args_.size()] = NULL;

    execv(args[0], const_cast<char**>(args));
  }

Is it OK to no free the allocated memory? as the child process will eventually end and the OS will reclaim the memory? and If I would like to free it anyways, how can I do it?

Thanks,

Kam
  • 5,878
  • 10
  • 53
  • 97

2 Answers2

3

All (user-allocated) memory allocated by a process is freed when the process is replaced with another by the execv call. Don't forget to check to make sure the call succeeded and handling that appropriately. If it fails you may want to free the memory then, or just exit if you do not need to do anything further.

execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded.

http://linux.about.com/od/commands/l/blcmdl2_execve.htm

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
1

It's always a good idea to free allocated memory. It might not cause any problems in any one particular instance, but if you fall into the habit of forgetting to free your memory, you will run into problems. You can free it by:

    for(size_t i = 0; i < args_.size(); ++i)
      delete[] args_[i];

    delete[] args_;
wolfPack88
  • 4,163
  • 4
  • 32
  • 47
  • Thank you for your answer. I know how to free the memory, I don't know where I need to free it? – Kam Jun 04 '14 at 18:32
  • Right after you're done using args_. In this case, right at the end of the `case 0` block. – wolfPack88 Jun 04 '14 at 18:33
  • 1
    If the execv call succeeded, the end of the case 0 block is never reached. If the execv failed, there are much bigger problems than a little memory leak. – David Hammen Jun 04 '14 at 19:58
  • @DavidHammen: You're right in this case, but like I said: "It might not cause any problems in any one particular instance, but if you fall into the habit of forgetting to free your memory, you will run into problems." Adding the deallocation chunk of your code doesn't detract anything from the rest of the code, but it does build good habits. – wolfPack88 Jun 04 '14 at 20:05