[Gambas-user] Gambas3 Pointers example - signal #6
John Spikowski
support at ...2529...
Wed Jan 19 07:08:28 CET 2011
On Tue, 2011-01-18 at 10:08 +0200, Demosthenes Koptsis wrote:
> >
> > Isn't pFunc a Gambas variable (memory location) which is maintained by
> > the Basic? Why would you free it externally? I would think Gambas would
> > complain about that.
>
> Yes pFunc is a pointer. A pointer is a variable that holds a memory
> address.
>
> At line
> Dim pFunc As Pointer
> i declare the variable.
>
> But i do not use Alloc() to alocate a memory address with Gambas3.
>
> i do this because the external function get_current_dir_name() allocates
> a memory address internal.
>
> This is described in manual
> http://manpages.ubuntu.com/manpages/dapper/en/man3/get_current_dir_name.3.html
>
> "get_current_dir_name, which is only prototyped if _GNU_SOURCE is
> defined, will malloc(3) an array"
>
> to free a pointer in such a case i have to use free() function of C.
>
> Next is the same example but with an error.
> The error is that i allocate memory with Gambas3 and try to Free() the
> memory later. But when i call get_current_dir_name() this function set
> again a new pointer and the address from Gambas3 Alloc() is not
> accesible any more. So when i try to Free() the pointer in fact i try to
> free an unlocated memory!
>
> ' Gambas module file
> 'char *get_current_dir_name(void);
> Extern get_current_dir_name() As Pointer In "libc:6"
>
> Public Sub Main()
>
> Dim pFunc As Pointer
> Dim sWorkingDirectory As String
>
> 'get_current_dir_name
> pFunc = Alloc(4096)
> Print pFunc '(Pointer 0x185b918)
>
> pFunc = get_current_dir_name()
> Print pFunc '(Pointer 0x185d780)
>
> 'notice that address was changed
> ' from now on the address 0x185b918
> 'is unreachable
> 'and the new address 0x185d780
> 'is not allocated by Gambas3 !
> 'so we cannot free both of them
> 'with Free() function of Gambas3!
>
> sWorkingDirectory = Str@(pFunc)
> Print sWorkingDirectory
>
> Free(pFunc)
> pFunc = 0
>
> End
I was thinking that you were freeing pFunc (using it's VARPTR) rather
than freeing the memory associated to the pointer being returned. I have
to agree with Benoît that working with external memory (variables) and
structures are a 'at your own risk' task in Gambas. (rules vary by what
your trying to access)
More information about the User
mailing list