Except it isn't sizeof(b) or '\0'. This actually passes the right length
to mbstowcs as well:
Index: wcsdup.3
===================================================================
RCS file: /cvs/src/lib/libc/string/wcsdup.3,v
retrieving revision 1.2
diff -u -p -r1.2 wcsdup.3
--- wcsdup.3 5 Jul 2011 19:01:31 -0000 1.2
+++ wcsdup.3 8 Jul 2011 15:50:50 -0000
@@ -61,9 +61,17 @@ The following will point
to an allocated area of memory containing the nul-terminated string
.Qq foobar :
.Bd -literal -offset indent
-wchar_t *p;
+const char *o = "foobar";
+wchar_t *p, b[32];
+size_t blen;
-if ((p = wcsdup(L"foobar")) == NULL) {
+blen = sizeof(b) / sizeof(b[0]);
+if (mbstowcs(b, o, blen) == (size_t)-1) {
+ fprintf(stderr, "Failed to convert string.\en");
+ exit(1);
+}
+b[blen - 1] = 0;
+if ((p = wcsdup(b)) == NULL) {
fprintf(stderr, "Out of memory.\en");
exit(1);
}
On Fri, Jul 08, 2011 at 04:16:03PM +0100, Nicholas Marriott wrote:
> On Fri, Jul 08, 2011 at 10:18:59AM +0200, Stefan Sperling wrote:
> > On Fri, Jul 08, 2011 at 03:01:45AM +0100, Nicholas Marriott wrote:
> > > Index: wcsdup.3
> > > ===================================================================
> > > RCS file: /cvs/src/lib/libc/string/wcsdup.3,v
> > > retrieving revision 1.2
> > > diff -u -p -r1.2 wcsdup.3
> > > --- wcsdup.3 5 Jul 2011 19:01:31 -0000 1.2
> > > +++ wcsdup.3 8 Jul 2011 02:01:22 -0000
> > > @@ -61,9 +61,14 @@ The following will point
> > > to an allocated area of memory containing the nul-terminated string
> > > .Qq foobar :
> > > .Bd -literal -offset indent
> > > -wchar_t *p;
> > > +const char *o = "foobar";
> > > +wchar_t *p, b[32];
> > >
> > > -if ((p = wcsdup(L"foobar")) == NULL) {
> > > +if (mbstowcs(b, o, sizeof(b)) == (size_t)-1) {
> > > + fprintf(stderr, "Failed to convert string.\en");
> >
> > s#\en#\n# in above line.
>
> We need \en to show \n in mdoc (the \e means \).
>
> >
> > I suppose wcsdup() relies on the string to be NUL-terminated?
> > If the return value of mbstowcs() equals sizeof(b) the string in b
> > is not NUL-terminated. We should probably add an example to the
> > mbstowcs() man page as well to make this abundantly clear.
>
> Yep. Hmm yep that sucks a bit. Well, I can add b[(sizeof b) - 1] = '\0'.
>
> >
> > In real code I'd probably use something like perror() or strerror() but
> > that's not what this page is about so I'm fine with fprintf(stderr, ...)
>
> Me too, but that's what was there already.
>
> >
> > > + exit(1);
> > > +}
> > > +if ((p = wcsdup(b)) == NULL) {
> > > fprintf(stderr, "Out of memory.\en");
> > > exit(1);
> > > }