ALLOCATE
来源: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgAllocate 最后更新: 2022-04-29
从空闲存储区分配一块内存。
语法
declare function Allocate cdecl ( byval count as uinteger ) as any ptr用法:
result = Allocate( count )参数
- count — 要分配的内存块大小(字节数)。
返回值
- 成功时:返回已分配内存起始地址。
- 失败时(count < 0 或内存不足):返回空指针(0)。
说明
从空闲存储区(堆)分配 count 字节的内存。新分配的内存未经初始化。
警告: Allocate 不可直接用于包含字符串的 String 或 UDT,因为字符串描述符未被清零(包含随机数据),可能导致数据损坏。在此类情况下,请使用:
Callocate(将内存清零)New Expression(调用构造函数,适用于 UDT)
返回的指针为 Any Ptr,指向已分配内存的起始位置。即使 count 为零,该指针也保证唯一。
已分配的内存在不再使用时必须通过 Deallocate 释放。
示例
vb
' Create a buffer of 15 integers, fill with Fibonacci numbers
Const integerCount As Integer = 15
Dim buffer As Integer Ptr
buffer = Allocate(integerCount * SizeOf(Integer))
If (0 = buffer) Then
Print "Error: unable to allocate memory, quitting."
End -1
End If
buffer[0] = 0
buffer[1] = 1
For i As Integer = 2 To integerCount - 1
buffer[i] = buffer[i - 1] + buffer[i - 2]
Next
For i As Integer = 0 To integerCount - 1
Print buffer[i];
Next
Deallocate(buffer)
End 0输出:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
内存泄漏示例(反面教材):
vb
Sub BadAllocateExample()
Dim p As Byte Ptr
p = Allocate(420) ' assign pointer to new memory
p = Allocate(420) ' reassign — old address is lost and that memory is leaked
Deallocate(p)
End Sub方言差异
- 在
-lang qb方言中不可用,除非使用别名__Allocate引用。
与 QB 的差异
- FreeBASIC 新增。