Ablenkungscode gekommen.
Praktisch ist der Code bei folgendem Problem: Wenn man mehrere Speicherblöcke gleichzeitig allokieren will und ein AllocateMemory()
fehltschlägt, dann bringen einem die schon zuvor allokierten Speicherblöcke
meist auch nichts mehr und man muss sie wieder freigeben.
Hier ist jetzt alles zusammengefasst.
Code: Alles auswählen
;info: MultiAllocateMemory
Procedure AllocateMemoryEx(*hnd.Long, Size.l, mode.l)
Structure AllocMem
*hnd.Long
Size.l
EndStructure
Static NewList AllocMem.AllocMem(), Count.l, allocated.l
Select mode
Case 1
If *hnd And Size
If AddElement(AllocMem())
*hnd\l = 0
AllocMem()\hnd = *hnd
AllocMem()\Size = Size
EndIf
EndIf
Case 2
SortStructuredList(AllocMem(), 1, SizeOf(AllocMem\Size), #PB_Sort_Long)
ForEach AllocMem()
AllocMem()\hnd\l = AllocateMemory(AllocMem()\Size)
If AllocMem()\hnd\l : allocated + 1 : EndIf
Count + 1
Next
If allocated = Count
ClearList(AllocMem())
ProcedureReturn #True
Else
ForEach AllocMem()
If AllocMem()\hnd\l : FreeMemory(AllocMem()\hnd\l) : EndIf
Next
ClearList(AllocMem())
ProcedureReturn #False
EndIf
EndSelect
EndProcedure
Macro AddMultiAllocateMemory(phnd, Size)
AllocateMemoryEx(phnd, Size, 1)
EndMacro
Macro MultiAllocateMemory()
AllocateMemoryEx(0, 0, 2)
EndMacro

KOMPLIZIERT
Code: Alles auswählen
a = AllocateMemory(100)
If a = 0 : End : EndIf
b = AllocateMemory(1000)
If b = 0 : FreeMemory(a) : End : EndIf
c = AllocateMemory(100000)
If c = 0 : FreeMemory(a) : FreeMemory(b) : End : EndIf
d = AllocateMemory(10000)
If d = 0 : FreeMemory(a) : FreeMemory(b) : FreeMemory(c) : End : EndIf
e = AllocateMemory(1000)
If e = 0 : FreeMemory(a) : FreeMemory(b) : FreeMemory(c) : FreeMemory(d) : End : EndIf
Debug "Es konnten alle Speicherblöcke allokiert werden:"
Debug a
Debug b
Debug c
Debug d
Debug e
Code: Alles auswählen
AddMultiAllocateMemory(@a, 100)
AddMultiAllocateMemory(@b, 1000)
AddMultiAllocateMemory(@c, 100000)
AddMultiAllocateMemory(@d, 10000)
AddMultiAllocateMemory(@e, 1000)
If MultiAllocateMemory()
Debug "Es konnten alle Speicherblöcke allokiert werden:"
Debug a
Debug b
Debug c
Debug d
Debug e
Else
Debug "Mindestens ein Speicherblock konnte nicht allokiert werden."
EndIf
Anregung dafür sehen, dass man immer wieder alles freigeben und
Rückgabewerte kontrollieren sollte.