Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to replace alloca in an implementation of execvp()?
    text
    copied!<p>Take a look at the NetBSD implementation of <code>execvp</code> here:</p> <p><a href="http://cvsweb.netbsd.se/cgi-bin/bsdweb.cgi/src/lib/libc/gen/execvp.c?rev=1.30.16.2;content-type=text%2Fplain" rel="nofollow">http://cvsweb.netbsd.se/cgi-bin/bsdweb.cgi/src/lib/libc/gen/execvp.c?rev=1.30.16.2;content-type=text%2Fplain</a></p> <p>Note the comment at line 130, in the special case for handling <code>ENOEXEC</code>:</p> <pre><code>/* * we can't use malloc here because, if we are doing * vfork+exec, it leaks memory in the parent. */ if ((memp = alloca((cnt + 2) * sizeof(*memp))) == NULL) goto done; memp[0] = _PATH_BSHELL; memp[1] = bp; (void)memcpy(&amp;memp[2], &amp;argv[1], cnt * sizeof(*memp)); (void)execve(_PATH_BSHELL, __UNCONST(memp), environ); goto done; </code></pre> <p>I am trying to port this implementation of <code>execvp</code> to standalone C++. <code>alloca</code> is nonstandard so I want to avoid it. (Actually the function I want is <code>execvpe</code> from FreeBSD, but this demonstrates the problem more clearly.)</p> <p>I think I understand why it would leak memory if plain <code>malloc</code> was used - while the caller of <code>execvp</code> can execute code in the parent, the inner call to <code>execve</code> never returns so the function cannot free the <code>memp</code> pointer, and there's no way to get the pointer back to the caller. However, I can't think of a way to replace <code>alloca</code> - it seems to be necessary magic to avoid this memory leak. I have heard that C99 provides variable length arrays, which I cannot use sadly as the eventual target is C++.</p> <p>Is it possible to replace this use of <code>alloca</code>? If it's mandated to stay within C++/POSIX, is there an inevitable memory leak when using this algorithm?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload