【发布时间】:2015-11-20 09:09:42
【问题描述】:
我想在 Swift 中将 UnsafeMutablePointer 的内容归零。
在 C 中你通常有这样的东西:
void freeSecure(void *buffer, uint64_t size) {
// Create volatile pointer to make sure that the code won't be optimized away
volatile uint8_t *ptr = buffer;
for (uint64_t i = 0; i < size; i++) ptr[i] = 0x00;
free(buffer);
}
如何在 Swift 中实现同样的功能?
// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
if num == 0 {
self.destroy()
self.dealloc(allocated)
return
}
let byteCount = sizeof(Memory) * allocated
let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
for var i = 0; i < byteCount; i++ {
ptr[i] = 0x00
}
self.destroy()
self.dealloc(allocated)
}
【问题讨论】:
-
你试过了吗?
-
这是我的实际代码,但我不知道它是否真的将数据清零或者是否删除了部分,因为数据将不再被读取...... ????
标签: swift compiler-optimization volatile