From: Ludovic Brenta <ludovic.brenta@insalien.org>
Subject: Re: Free-ing memory: not springing leaks?
Date: 14 Sep 2003 16:24:36 +0200
Date: 2003-09-14T16:24:36+02:00 [thread overview]
Message-ID: <m31xujcusb.fsf@insalien.org> (raw)
In-Reply-To: WMZ8b.2006$WI3.27207@newsfep4-glfd.server.ntli.net
chris <spamoff.danx@ntlworld.com> writes:
> Matthew Heaney wrote:
> > If you know it was malloc'd, then yes, just write a binding to free and
> > call that.
>
> And if you don't, then it's hit and miss? ... it figures. I wonder
> how C programmers deal with this :(
This is supposedly documented by your library. Some libraries return
"statically allocated" memory which you must not free. This is for
example the case of readdir(3).
In the particular case of dlerror(3), I've just had a look at the
sources because the documentation is very evasive about this. As it
turns out, dlerror() runs in one of two modes, thread-safe or not.
In thread-safe mode, it allocates a dynamic block of memory for each
thread. This block contains a pointer to the string returned. The
function allocates and frees this pointer, and _you should not free
the memory yourself_, because you cannot set the pointer to NULL
(remember that C is pass-by-value only, so what you receive from
dlerror() is a copy of the pointer).
If for some reason, dlerror() cannot use thread-safe mode, it falls
back to a thread-unsafe mode in which there is a single, statically
allocated, block of memory containing the pointer to the error string.
As before, dlerror() allocates and frees the memory for the string.
If you wand to forcefully free the memory, your best bet is to call
dlerror() twice, like this (I have not tried to compile this, mind
you):
Dynamic_Loader_Error : Exception;
procedure Dl_Error is
function dlerror returns Interfaces.C.Strings.chars_ptr;
pragma Import (C, dlerror, "dlerror");
Error_Message : Interfaces.C.Strings.chars_ptr := dlerror;
use type Interfaces.C.Strings.chars_ptr;
begin
if Error_Message /= Interfaces.C.Strings.Null_Ptr then
declare
S : String := Interfaces.C.Strings.Value (Error_Message);
begin
Error_Message := dlerror; -- ask it to free the memory
Ada.Exceptions.Raise_Exception (Dynamic_Loader_Error'Identity, S);
end if;
end if;
end Dl_Error;
--
Ludovic Brenta.
next prev parent reply other threads:[~2003-09-14 14:24 UTC|newest]
Thread overview: 12+ messages / expand[flat|nested] mbox.gz Atom feed top
2003-09-13 21:33 Free-ing memory: not springing leaks? chris
2003-09-14 1:10 ` Matthew Heaney
2003-09-14 11:02 ` chris
2003-09-14 12:51 ` Matthew Heaney
2003-09-14 12:14 ` chris
2003-09-14 14:24 ` Ludovic Brenta [this message]
2003-09-14 19:00 ` chris
2003-09-14 16:06 ` Simon Wright
2003-09-15 7:13 ` Martin Krischik
2003-09-18 20:15 ` Warren W. Gay VE3WWG
2003-09-19 3:02 ` Hyman Rosen
2003-09-19 13:07 ` Warren W. Gay VE3WWG
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox