释放以前赋值的内存
语法
用法
Deallocate( pointer )
参数
说明
此过程可以释放先前使用
Allocate赋值的内存。
pointer 必须是有效的指针。过程返回后,
pointer 将被无效(指向无效的内存地址),并且使用(再次引用或再次调用
Deallocate)将导致未定义的行为。
在空指针上调用
Deallocate不会导致任何操作。
Deallocate是C运行时库
free的别名,因此不能保证在所有平台中都是线程安全的。
例子
以下示例显示如何释放以前赋值的内存。请注意,在释放赋值之后,该指针设置为null:
Sub DeallocateExample1()
Dim As Integer Ptr integerPtr = Allocate( Len( Integer ) ) ''初始化指针
''新的内存地址
*integerPtr = 420 ''使用指针
Print *integerPtr
Deallocate( integerPtr ) ''免费内存回系统
integerPtr = 0 ''并将该指针置零
End Sub
DeallocateExample1()
End 0
虽然在这种情况下,这是不必要的,因为函数立即退出,将指针设置为null是一个很好的习惯。如果函数从通过引用传入的指针中释放内存,例如,在函数调用中使用的指针将被无效,并且由调用者重新赋值指针或将其设置为null。示例3显示了如何正确处理这种情况,下一个示例显示了使用多个引用释放内存的效果。
在以下示例中,使用不同的指针来释放以前赋值的内存。
''警告:“邪恶”的例子显示了不应该做的事情
Sub DeallocateExample2()
Dim As Integer Ptr integerPtr = Allocate( Len( Integer ) )
''初始化^^^指向新内存的指针
Dim As Integer Ptr anotherIntegerPtr = integerPtr
''初始化^^^另一个指向同一个内存的指针
*anotherIntegerPtr = 69 ''使用其他指针
Print *anotherIntegerPtr
Deallocate( anotherIntegerPtr ) ''免费内存回系统
anotherIntegerPtr = 0 ''和零其他指针
'' *integerPtr = 420 ''未定义的行为;原版的
''指针无效
End Sub
DeallocateExample2()
End 0
请注意,在解除赋值后,
both 指针将无效。这说明了使用指针时可能会出现错误的另一种方法。作为一般规则,只有当您知道只有一个(1)指针当前指向它时,才释放先前赋值的内存。
Function createInteger() As Integer Ptr
Return Allocate( Len( Integer ) ) ''返回指针到新的
End Function ''赋值内存
Sub destroyInteger( ByRef someIntegerPtr As Integer Ptr )
Deallocate( someIntegerPtr ) ''免费内存回系统
someIntegerPtr = 0 ''空原指针
End Sub
Sub DeallocateExample3()
Dim As Integer Ptr integerPtr = createInteger() ''初始化指针
''新的内存地址
*integerPtr = 420 ''使用指针
Print *integerPtr
destroyInteger( integerPtr ) ''通过引用传递指针
Assert( integerPtr = 0 ) ''指针现在应该为null
End Sub
DeallocateExample3()
End 0
在上面的程序中,函数中的引用指针在释放指向的内存后被设置为null。使用
断言宏来测试函数调用后原始指针是否为空。此示例意味着将指针传递给通过引用释放指定的内存的函数的正确方法。
方言差异
与QB差别
参考