allocate some memory in swift

To allocate memory dynamically in Swift, you can use the UnsafeMutableRawPointer type along with the malloc function from the C standard library. Here's an example of how to allocate 100 bytes of memory using malloc:

main.swift
let byteCount = 100
let rawPointer = UnsafeMutableRawPointer.allocate(byteCount: byteCount)
92 chars
3 lines

This creates a mutable raw pointer (UnsafeMutableRawPointer) pointing to the start of the allocated memory block. You can access the memory through this pointer like so:

main.swift
for i in 0..<byteCount {
  rawPointer.advanced(by: i).storeBytes(of: UInt8(i), as: UInt8.self)
}

for i in 0..<byteCount {
  print(rawPointer.load(fromByteOffset: i, as: UInt8.self))
}
185 chars
8 lines

This code stores the values 0 through 99 sequentially into the allocated memory block, and then prints them out to show that they were properly stored and can be read back out.

To free the allocated memory block when you're done with it, use the free function:

main.swift
rawPointer.deallocate()
24 chars
2 lines

This deallocates the memory previously reserved with malloc.

gistlibby LogSnag