c++memoryshared-ptrsmart-pointersexecv

When are smart pointers' memory cleared on calling execv() in a program?


I was trying to understand when the memory owned by shared (smart) pointers are cleared on calling execv() from the code.


Assume the following code:

#include <memory>

class Test { public: ~Test() { std::cout << "Test destroyed."; } };

int main() {
  std::shared_ptr<Test> p = std::make_shared<Test>();
  std::shared_ptr<Test> q = p;

  p.reset();

  // Call execv().
  execv("/bin/program", "/bin/program");

  // This code will never be executed, because execv() replaces the current process image.
  // Will the memory pointed to by q be cleared?
  return 0;
}

On calling execv("/bin/program", "/bin/program"); the current process image is replaced with the new process image.
My question is will the memory owned by the shared pointer be cleared or not when the new process starts or should we call q.reset() explicitly before calling execv("/bin/program", "/bin/program");?

I tried looking at the documentation of execv() but could not find any mention of smart pointers.


Solution

  • Syscalls like execve or the computer catching fire are an "out of context" problem for C++. When you call execve, the program flow transitions to the kernel. The kernel completely reinitializes the memory space and the original program does not get a chance to run again. The smart pointer and the memory it used to manage simply ceases to exist.

    If you wanted to use the smart pointer's release action to perform side effects that are visible outside of the program (eg file or network I/O), release them by hand before calling execve.