Subject: Re: magic symlinks: uid keyword translation
To: None <tech-kern@NetBSD.org>
From: Christian Biere <christianbiere@gmx.de>
List: tech-kern
Date: 10/30/2006 19:42:45
Joerg Sonnenberger wrote:
> On Mon, Oct 30, 2006 at 04:59:54PM +0100, Christian Biere wrote:
> > Too bad, you can only return structs but not plain strings in C.
> 
> hugh? I certainly have functions which return strings and libc has as
> well. E.g. strstr.

Those return a pointer to a string.

What I had in mind is something like this:


	printf("%s", uid_to_string(uid));

but without resorting to a static buffer (or heap-allocated) buffer.

You could write code like this:

	typedef struct uid_string_buf {
  		char str[PROPER_LENGTH_FOR_A_DECIMAL_UID];
	} uid_string_buf_t;

	uid_string_buf_t
	uid_to_string(uid_t uid)
	{
		uid_string_buf_t buf;
		snprintf(buf.str, sizeof buf.str, [...]);
		return buf;
	}

	uid_string_buf_t uid_str;

	uid_str = uid_to_string(uid);
	printf("%s", uid_str.str);

So everything is stack-based. No worries about leaks or buffer sizes.
Of course, the additionally required variable is somewhat awkward
but you can't even write this, unfortunately:

	printf("%s", uid_to_string_buf(uid).str); /* not legal */

-- 
Christian