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.swift92 chars3 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.swift185 chars8 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.swift24 chars2 lines
This deallocates the memory previously reserved with malloc
.
gistlibby LogSnag