On Wednesday, 31 July 2013 at 08:20:48 UTC, deadalnix wrote:
On Wednesday, 31 July 2013 at 07:54:00 UTC, monarch_dodra wrote:
I want to point out that one of the dangers (as I've heard it, I haven't actually run into this), is that since the garbage collector won't scan your C function's internals, the caller *must* keep a reference in his code to preserve the allocated array. The above scheme does not do that: If the garbage collector runs after the start of the call, but before the end of the function, then you are in trouble.


You have to work very hard to not find it either in the stack or in a register during the function call. So as long as the C code do not keep a reference, ou should be fine.

I'd do it like this:
//----
string lifeline = toStringz("hello"); //Preserve reference
c_function(lifeline.ptr); //Make call
lifeline = null; //Release reference
//----


This is plain useless. dead store elimination will remove the "release reference", the variable lifeline promoted to register (its ptr part anyway, it length part is likely to be trashed right away by the function call).

On X86, the string will be returned in EAX and EDX (ptr in EDX if I'm not mistaken). So the length will be erased by copying EDX to EAX (now both contains the ptr, length is lost) and the call made right away (first argument is passed in EAX).

I'll take your word for it then. As I said, I didn't run into this before, but I had read some other posts that mentioned this problem. I might have it confused with dynamic libs though?

I don't know. Forget I said anything then.

That's assuming c_function won't preserve the string somewhere. If it does, things get more complicated.

If it does, that means big trouble, even in pure C, as it is now unclear who is the owner of the string. A recipe for memory corruption/leak.

Most probably.

Reply via email to