Say I want to run a function and avoid it from memory leak, which may happen because the function actually result in memory leak, or because I need to kill it.
I currently use a new process on linux to separate two address spaces, and it works fine:
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
template<class F>
int execute(F& f) {
int* shm = (int*)mmap(0, 64, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pid_t pid = fork();
if (shm == 0 || pid < 0) {
munmap(shm, 64);
throw "Error executing";
}
if (pid == 0) {
*shm = f();
exit(0);
}
int status;
waitpid(pid, &status, 0);
int ret = *shm;
munmap(shm, 64);
return ret;
}
int testfunc() {
// Memory leak
for (int i=0; i<1048576; ++i) (new int[1024])[28] = 77;
return 42;
}
int main() {
while(1)
printf ("%dn", execute(testfunc));
}
- How to do this on windows?
- Is there better or worth-compare solution on linux?