[Gambas-user] [Fwd: Gambas3 Pointers example] signal #6

Benoît Minisini gambas at ...1...
Mon Jan 17 11:08:51 CET 2011


> Here is a last case about pointers i found.
> 
> CASE 1
> -------
> When a C++ function does not malloc any memory it may return a pointer.
> In this case we can do
> 
> DIM pPointer as Pointer
> pPointer = Alloc(4096)' alloc 4096 bytes
> 
> pPointer = getwd(pBuf)
> 
> 'use pPointer with Str@() or other xxx@()
> 
> Free(pPointer)
> pPointer=0
> 
> OK!
> 
> CASE 2
> -------
> When a c++ function itself allocate memory with malloc() what can we do?
> 
> Example.
> --------
> ' 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 '0xc12938
> 
>   pFunc = get_current_dir_name()
>   Print pFunc '0xc147a0
> 
>   'now we cannot Free(pFunc) it is not 0xc12938 anymore
>   'get_current_dir_name() malloc itself memory and return a new pointer
> 
>   sWorkingDirectory = Str@(pFunc)
>   Print sWorkingDirectory
> 
> ' Free(pFunc)
> 'if i unrem Free i get a crash, because i try to free the 0xc147a0
>   pFunc = 0
> 
> End
> 
> What can we do in such cases when a function itself allocates memory?
> Should we free it? Can we?
> 
> May be we can use pointers without Alloc()?
> 
> Example, no Alloc(), no Free, just DIM pPointer
> ---------
> ' 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 = get_current_dir_name()
>   Print pFunc '0xc147a0
> 
>   sWorkingDirectory = Str@(pFunc)
>   Print sWorkingDirectory
> 
>   pFunc = 0
> 
> End
> 

What must be done with with a pointer returned by a C / C++ function depends 
on the function semantic.

You must read and *understand* the function documentation to know.

Some functions return a pointer that you must free yourself with Free().

Some functions return a pointer that you must not free.

Some functions return a pointer that you must free by calling a dedicated 
function, and not Free().

... Everything is possible.

Regards,

-- 
Benoît Minisini




More information about the User mailing list