This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

RE: Garbage collection and C structures


Hi.  I'm using Guile in a C program.  I've been having mysterious segfaults
recently that seemed to be occuring in the garbage collector.  I think that I've
finally worked out what the problem is; I had a heap-allocated variable that
contained a char* pointer which I wanted to return to Scheme; to do so, I
did:

  return gh_str02scm( data->string );

  With this code, my program would periodically segfault.

So does mine.  I added code to chase memory faults, only
to cause them to go away.  (Allocation algorithms behave differently
when every allocation has 16 bytes of overhead.)

[[...]]   I assume that this is because Guile doesn't make
copies of data you give it but instead stores a pointer which is used for
No, actually it does dup your string.  So, if your string is allocated, you
need to free it yourself.
 GC-ing; it garbage-collected the data but then I asked for it again, causing
a segfualt.  I think this should be documented very clearly in the section on
converting data between C and Scheme because it isn't obvious which behavior
is used,

Amen!

 and there are two big pitfalls with the assumption I made:


(b) Almost worse, I was expecting that the Scheme objects would stay constant if
   I changed the C variables.  I haven't tested this, but I suppose (given that
   they appear to be the same as the C variables) that they won't.  This would
   probably have broken my code in much more subtle ways if I hadn't been
   tripped up by the segfault. (conversely, I guess I could find creative
   ways to make use of this. ;-) )
 
This should only happen with *shared* strings.  gh_str02scm() makes a private copy.

> Basically, I think this issue and similar issues of pointer ownership should
>  be merged into the Guile documentation as soon as someone has time.    [sooner!]
> It would've saved me a couple of hours of frustration at any rate.  [me too! ]-:

 - Bruce