chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] c-string return question


From: John Cowan
Subject: Re: [Chicken-users] c-string return question
Date: Thu, 13 Oct 2011 12:50:56 -0400
User-agent: Mutt/1.5.18 (2008-05-17)

Jörg F. Wittenberger scripsit:

> (define integer->utf8string
>  (foreign-lambda*
>   c-string ((unsigned-integer ch))
>   "static C_uchar off[6]={0xFC,0xF8,0xF0,0xE0,0xC0,0x00};
>  int size=5; C_uchar buf[7];
>  buf[6]='\\0';
>  if (ch < 0x80) {
>    buf[5]=ch;
>  } else {
>    buf[size--]=(ch&0x3F)|0x80; ch=ch>>6;
>    while (ch) { buf[size--]=(ch&0x3F)|0x80; ch=ch>>6; }
>    /* Write the size information into the first byte */
>    ++size;
>    buf[size]=off[size]|buf[size];
>  }
>  return(buf+size);
> "))

This code is not good C, because it returns a pointer into a stack
frame which has already been exited.  It may just so happen that
there is still a correct value there, but there are no guarantees.
I'd guess that the corruption happens when there is a minor GC.
See http://c-faq.com/~scs/cclass/int/sx5.html .

> 1.) static C_uchar buf[7];
>    ^^^^^^
>    does the trick.

That's absolutely the Right Thing.  You are now returning a pointer to
the static data region, which will always be available.

-- 
John Cowan  address@hidden   http://ccil.org/~cowan
Consider the matter of Analytic Philosophy.  Dennett and Bennett are well-known.
Dennett rarely or never cites Bennett, so Bennett rarely or never cites Dennett.
There is also one Dummett.  By their works shall ye know them.  However, just as
no trinities have fourth persons (Zeppo Marx notwithstanding), Bummett is hardly
known by his works.  Indeed, Bummett does not exist.  It is part of the function
of this and other e-mail messages, therefore, to do what they can to create him.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]