How to allocate 1MB in Swift

3 Answers

0 votes
import Foundation

// Allocates 1MB of memory = 1,048,576 bytes
var buffer = [UInt8](repeating: 0, count: 1024 * 1024) 

print("Allocated \(buffer.count) bytes.")




/*
run:

Allocated 1048576 bytes.

*/

 



answered May 20, 2025 by avibootz
0 votes
import Foundation

// Allocates 1MB of memory = 1,048,576 bytes
let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1024 * 1024) 

print("Allocated 1MB of memory using UnsafeMutablePointer.")

pointer.deallocate() // Free memory after use




/*
run:

Allocated 1MB of memory using UnsafeMutablePointer.

*/

 



answered May 20, 2025 by avibootz
0 votes
import Foundation

// Allocates 1MB of memory = 1,048,576 bytes
let dataBuffer = Data(count: 1024 * 1024)

print("Allocated \(dataBuffer.count) bytes using Data.")



/*
run:

Allocated 1048576 bytes using Data.

*/

 



answered May 20, 2025 by avibootz

Related questions

2 answers 151 views
3 answers 179 views
1 answer 131 views
131 views asked May 20, 2025 by avibootz
3 answers 196 views
3 answers 204 views
204 views asked May 20, 2025 by avibootz
1 answer 111 views
111 views asked May 20, 2025 by avibootz
...