Page 1 of 1
Return pointer to new variable in procedure
Posted: Wed Jun 17, 2020 6:01 pm
by wb2k
I want to create a pointer to a new variable in a procedure. When declaring the variable with Static the content of the variable is overwritten on the second run which seems to what the
documentation of Static says that the variable isn't reinitialized:
Code: Select all
Structure sum
sum.i
EndStructure
Procedure add(a,b)
Static foo.sum
foo\sum = a+b
ProcedureReturn @foo
EndProcedure
*aaa.sum = add(1,2)
Debug *aaa\sum
*bbb.sum = add(3,4)
Debug *bbb\sum
Debug *aaa\sum
aaa.sum is correctly set to 3, then bbb.sum is correctly set to 7, but also aaa.sum is (wrongly) set to 7.
However, when using Protected where the variable would be reinitialized every time the debug output shows which seems to be a pointer and also 3 times the same pointer-address.
Does anyone have an idea how I can achieve this?
Re: Return pointer to new variable in procedure
Posted: Wed Jun 17, 2020 6:15 pm
by infratec
If you want a new 'variable' you have to create it.
And... free it.
Code: Select all
Procedure add(a,b)
Protected *a.integer
*a = AllocateMemory(SizeOf(Integer))
*a\i = a+b
ProcedureReturn *a
EndProcedure
Define *a.Integer, *b.Integer
*a = add(1,2)
Debug *a\i
*b = add(3,4)
Debug *b\i
Debug *a\i
FreeMemory(*a)
FreeMemory(*b)
Re: Return pointer to new variable in procedure
Posted: Wed Jun 17, 2020 6:34 pm
by wb2k
Thank you very much infratec!
So here is the working example with the structure (without freeing memory):
Code: Select all
Structure sum
sum.i
EndStructure
Procedure add(a,b)
Protected *foo.sum
*foo = AllocateMemory(SizeOf(sum))
*foo\sum = a+b
ProcedureReturn *foo
EndProcedure
*aaa.sum = add(1,2)
Debug *aaa\sum
*bbb.sum = add(3,4)
Debug *bbb\sum
Debug *aaa\sum
Re: Return pointer to new variable in procedure
Posted: Thu Jun 18, 2020 7:09 am
by mestnyi
infratec wrote:If you want a new 'variable' you have to create it.
And... free it.
Code: Select all
Procedure add(a,b)
Protected *a.integer
*a = AllocateMemory(SizeOf(Integer))
*a\i = a+b
ProcedureReturn *a
EndProcedure
Define *a.Integer, *b.Integer
*a = add(1,2)
Debug *a\i
*b = add(3,4)
Debug *b\i
Debug *a\i
FreeMemory(*a)
FreeMemory(*b)
I do not see to be freed.
Code: Select all
Procedure add(a,b)
Protected *a.integer
*a = AllocateMemory(SizeOf(Integer))
*a\i = a+b
ProcedureReturn *a
EndProcedure
Define *a.Integer, *b.Integer
*a = add(1,2)
Debug *a\i
*b = add(3,4)
Debug *b\i
Debug *a\i
Debug "free"
FreeMemory(*a)
FreeMemory(*b)
Debug *b\i
Debug *a\i
Re: Return pointer to new variable in procedure
Posted: Thu Jun 18, 2020 10:16 am
by mk-soft
The last access takes place on not yet overwritten memory. May lead to memory access errors.
It is easier to transfer the result via parameter ByRef
Code: Select all
Procedure add(a, b, *result.integer)
*result\i = a + b
EndProcedure
Define a.i = 10
Define b.i = 20
Define c.i
add(a, b, @c)
Debug c