swiftpointersmallocalloc

Pointer and malloc in Swift


I am trying to convert this into swift.

Facing issue at memory allocation logic

Byte *p[10000];

p[allocatedMB] = malloc(1048576);
memset(p[allocatedMB], 0, 1048576);

How to write this in swift?


Solution

  • You can use malloc from Swift, it returns a "raw pointer":

    var p: [UnsafeMutableRawPointer?] = Array(repeating: nil, count: 10000)
    var allocatedMB = 0
    
    p[allocatedMB] = malloc(1048576)
    memset(p[allocatedMB], 0, 1048576)
    

    Alternatively, use UnsafeMutablePointer and its allocate and initialize methods:

    var p: [UnsafeMutablePointer<UInt8>?] = Array(repeating: nil, count: 10000)
    var allocatedMB = 0
    
    p[allocatedMB] = UnsafeMutablePointer.allocate(capacity: 1048576)
    p[allocatedMB]?.initialize(to: 0, count: 1048576)