Correct way to call execve?

Marc Olzheim marcolz at stack.nl
Tue Jul 22 04:54:39 PDT 2003


On Mon, Jul 21, 2003 at 11:24:43AM -0700, Tim Kientzle wrote:
> Chad David wrote:
> >I assumed it was obvious that you could copy the data, but I believe
> >the intent of the original question was to find an alternative.  As
> >far as I know there isn't one.  A const is a const, except in C++.
> 
> Yes, the intent was to find a way to avoid copying the data.
> 
> I was hoping that someone knew a standard way to
> say "yes, I really do mean to cast away that const,"
> akin to C++ const_cast.
> 
> As far as I can tell, the POSIX-mandated declaration
> of execvp is simply wrong.  (SUSv3 even has a comment
> that essentially admits this fact and then vainly tries
> to rationalize it.  <sigh>)

I mailed this a long time ago:

char	*
func(void)
{
	char		*foo;
	const char	*cfoo = "bar";

	/*  From http://www.eskimo.com/~scs/C-faq/q11.10.html:
	 *
	 *  References: ANSI Sec. 3.1.2.6, Sec. 3.3.16.1, Sec. 3.5.3 
	 *  ISO Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3 
	 *  H&S Sec. 7.9.1 pp. 221-2
	 *
	 *  Use -Wcast-qual with gcc.
	 *  gcc 2.7.2.3 ok, gcc 2.95.2 not ok.
	 */
	foo = *((char *const *) &cfoo);

	return (foo);
}

But that doesn't work after 2.7.2

What does work, except with 2.95 is this:

	foo = *((char **)((void *)&cfoo)));

Then again: you can always use the union trick:

	union
	{
		void		*nonconst;
		const	void	*constant;
	} hack;

	hack.constant = cfoo;
	foo = hack.nonconst;

Zlo


More information about the freebsd-hackers mailing list