线程1:致命错误:UnsafeMutablePointer.initialize重叠范围

时间:2018-09-04 23:37:34

标签: ios iphone swift xcode

我正在尝试使用

UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!

因为它是我需要使用的方法的参数所必需的。但是我不知道这是什么或如何使用。

我通过执行以下操作创建了此值:

 var bytes2: [Float] = [39, 77, 111, 111, 102, 33, 39, 0]
    let uint8Pointer2 = UnsafeMutablePointer<Float>.allocate(capacity: 8)
    uint8Pointer2.initialize(from: &bytes2, count: 8)

    var bytes: [Float] = [391, 771, 1111, 1111, 1012, 331, 319, 10]
    var uint8Pointer = UnsafeMutablePointer<Float>?.init(uint8Pointer2)
    uint8Pointer?.initialize(from: &bytes, count: 8)

    let uint8Pointer1 = UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!.init(&uint8Pointer)
    uint8Pointer1?.initialize(from: &uint8Pointer, count: 8)

但是我得到了错误:

Thread 1: Fatal error: UnsafeMutablePointer.initialize overlapping range

我在做什么错?

1 个答案:

答案 0 :(得分:2)

您正在制造不良行为。

var bytes2: [Float] = [39, 77, 111, 111, 102, 33, 39, 0]
let uint8Pointer2 = UnsafeMutablePointer<Float>.allocate(capacity: 8)
uint8Pointer2.initialize(from: &bytes2, count: 8)

创建指向某些内存的指针,并将该内存初始化为存储在bytes2中的值。

所以:uint8Pointer2 = [39, 77, 111, 111, 102, 33, 39, 0]


然后,您决定创建一个引用该指针的内存的指针:

var uint8Pointer = UnsafeMutablePointer<Float>?.init(uint8Pointer2)

因此,如果您打印uint8Pointer,它将具有与uint8Pointer2完全相同的值。如果您决定也更改其任何值,它也会更改{{ 1}} ..

因此,当您这样做时:

uint8Pointer2

它用var bytes: [Float] = [391, 771, 1111, 1111, 1012, 331, 319, 10] uint8Pointer?.initialize(from: &bytes, count: 8) 覆盖了uint8Pointer2的值。.


到目前为止,[391, 771, 1111, 1111, 1012, 331, 319, 10]只是uint8Pointer的浅表副本。改变一个会影响另一个。.

现在您决定这样做:

uint8Pointer2

这里您创建了指向{{1}的指针(let uint8Pointer1 = UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!.init(&uint8Pointer) uint8Pointer1?.initialize(from: &uint8Pointer, count: 8) ),并说uint8Pointer1uint8Pointer进行了初始化。但是您正在初始化一个指向自身的指针并计数为8。

首先,不要费心在指向具有自身值的指针的指针上调用Initialize。它已经指向了正确的值。

那很好:

uint8Pointer1

将崩溃,但是:

uint8Pointer

不会..因为它不会为后者做uint8Pointer1?.initialize(from: &uint8Pointer, count: 1) //Same as: memcpy(uint8Pointer1, &uint8Pointer, sizeof(uint8Pointer)` //However, they both point to the same memory address.. 。而前者却不会。

希望我能正确解释。

P.S。正确命名您的变量!


C ++人士的翻译:

uint8Pointer1?.initialize(from: &uint8Pointer)
//Same as: `uint8Pointer1 = uint8Pointer`.. Note: Just a re-assignment.