I was particularly surprised that ReAllocateMemory() accepts a null pointer. Surely if this is not safe, then the compiler should raise an exception?
Code: Select all
EnableExplicit
; Memory allocation / structure pointer initialisation
; This works, but is it safe?
Structure AStruct
iVal.i
*AMemoryBlock
qVal.q
*IntegerPointer.Integer
EndStructure
Declare Main()
Declare.i Init(*MyStruct.AStruct)
End Main()
Procedure Main()
Protected MyStruct.AStruct
MyStruct\iVal=$01234567
MyStruct\qVal=$0123456789ABCDEF
Debug("MyStruct\AMemoryBlock=$"+Hex(MyStruct\AMemoryBlock))
Init(@MyStruct)
If MyStruct\AMemoryBlock
Debug("MyStruct\AMemoryBlock=$"+Hex(MyStruct\AMemoryBlock))
Debug("MemorySize(MyStruct\AMemoryBlock)="+Str(MemorySize(MyStruct\AMemoryBlock)))
ShowMemoryViewer(MyStruct\AMemoryBlock,MemorySize(MyStruct\AMemoryBlock))
EndIf
Debug("MyStruct\iVal=$"+Hex(MyStruct\iVal))
Debug("MyStruct\qVal=$"+Hex(MyStruct\qVal))
Debug("MyStruct\IntegerPointer\i=$"+Hex(MyStruct\IntegerPointer\i))
ProcedureReturn
EndProcedure
Procedure.i Init(*MyStruct.AStruct)
Debug("Before realloc, *MyStruct\AMemoryBlock=$"+Hex(*MyStruct\AMemoryBlock))
*MyStruct\AMemoryBlock=ReAllocateMemory(*MyStruct\AMemoryBlock,131072)
Debug("After realloc, *MyStruct\AMemoryBlock=$"+Hex(*MyStruct\AMemoryBlock))
If *MyStruct\AMemoryBlock
FillMemory(*MyStruct\AMemoryBlock,MemorySize(*MyStruct\AMemoryBlock),$A55A5AA5,#PB_Long)
EndIf
*MyStruct\iVal=$01234567
*MyStruct\qVal=$0123456789ABCDEF
*MyStruct\IntegerPointer=AllocateStructure(Integer)
*MyStruct\IntegerPointer\i=$76543210
ProcedureReturn
EndProcedure
Code: Select all
MyStruct\AMemoryBlock=$0
Before realloc, *MyStruct\AMemoryBlock=$0
After realloc, *MyStruct\AMemoryBlock=$4730048
MyStruct\AMemoryBlock=$4730048
MemorySize(MyStruct\AMemoryBlock)=131072
MyStruct\iVal=$1234567
MyStruct\qVal=$123456789ABCDEF
MyStruct\IntegerPointer\i=$76543210
[Using PB 6.21, Windows 11]