2

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?

craft
  • 2,017
  • 1
  • 21
  • 30
user1101733
  • 258
  • 2
  • 14
  • To expand on Martin's answer (+1), I might also encourage the use of Swift feature `_` to make those big numbers more readable, e.g. `malloc(1_048_576)`, to make it easier to read at a glance. – Rob Feb 10 '18 at 21:50
  • 1
    ... or in this case, `1024*1024` – Martin R Feb 10 '18 at 21:57
  • See "[“Please convert my code to X” questions](https://meta.stackexchange.com/questions/54345/please-convert-my-code-to-x-questions)" – the Tin Man Apr 16 '20 at 00:21
  • **See for example: [Swift way to convert Data to Hex?](https://stackoverflow.com/posts/69477135/edit)** (which uses `UnsafeMutablePointer.allocate`) – Top-Master Oct 07 '21 at 12:36

1 Answers1

6

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)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks Martin! Could you please let me know the resources or example to learn more about UnsafeMutableRawPointer in swift? – user1101733 Feb 10 '18 at 22:42
  • I am using first way (using malloc) - Getting "Message from debugger: Terminated due to memory issue" message on debugger after allocation of around 600MB. Total available memory is 1.96GB. – user1101733 Feb 10 '18 at 23:15
  • using both way userMemory is not increasing after allocating 1 object. I am repeatedly allocating memory by using this code snippet in loop. – user1101733 Feb 13 '18 at 18:42