Ios 使用malloc/free的崩溃EXC\u错误访问

Ios 使用malloc/free的崩溃EXC\u错误访问,ios,objective-c,malloc,Ios,Objective C,Malloc,我有一些优化代码崩溃。我试图做的是,当上一个点和下一个点足够接近时,从输入数组中删除一些点。该方法在几乎所有情况下都能很好地工作,但在某些特定数据下会崩溃 崩溃的输入数据示例: Value of coords : (51.55188, -0.17591), (51.55208, -0.17516), (51.55231, -0.17444) Value of altitudes : 10000, 10000, 10000 Value of count : 3 如果我跳过优化代码并直接使用输入值

我有一些优化代码崩溃。我试图做的是,当上一个点和下一个点足够接近时,从输入数组中删除一些点。该方法在几乎所有情况下都能很好地工作,但在某些特定数据下会崩溃

崩溃的输入数据示例:

Value of coords : (51.55188, -0.17591), (51.55208, -0.17516), (51.55231, -0.17444)
Value of altitudes : 10000, 10000, 10000
Value of count : 3
如果我跳过优化代码并直接使用输入值,则一切正常。如果我只是在临时数组中存储输入值,它也可以正常工作

我得到了一个EXC_BAD_ACCESS EXC_I386_GPFLT,在使用此方法并发布输入数据之后。崩溃不是直接发生在这个方法中,而是在我使用在方法末尾创建的对象之后。我已经尝试过NSZombie和僵尸评测。几乎所有的数据都能正常工作,但是这个特定的输入数据会100%崩溃,至少我更容易调试

我的方法代码:

+ (instancetype) optimizedPolylineWithCoordinates:(CLLocationCoordinate2D*) coords altitudes:(RLMKAltitude*) altitudes count:(NSUInteger) count
{
    CGFloat minimumDistanceBetweenPoints = [self minimumOptimizedDistanceBetweenPoints];

    CLLocationCoordinate2D* tempCoords = malloc(sizeof(CLLocationCoordinate2D) * count);
    RLMKAltitude* tempAltitudes = malloc(sizeof(RLMKAltitude) * count);
    NSUInteger tempCoordsCount = 0;

    // Always keep first point
    tempCoords[0] = coords[0];
    tempAltitudes[0] = altitudes[0];
    ++tempCoordsCount;

    for (NSUInteger i = 1; i < (count - 1); i++)
    {
        MKMapPoint prevPoint = MKMapPointForCoordinate(coords[i - 1]);
        MKMapPoint nextPoint = MKMapPointForCoordinate(coords[i + 1]);

        // Get the distance between the next point and the previous point.
        CLLocationDistance distance = MKMetersBetweenMapPoints(nextPoint, prevPoint);

        // Keep the current point if the distance is greater than the minimum
        if (distance > minimumDistanceBetweenPoints)
        {
            tempCoords[tempCoordsCount] = coords[i];
            tempAltitudes[tempCoordsCount] = altitudes[i];
            ++tempCoordsCount;
        }
    }  

    // Always keep last point
    tempCoords[tempCoordsCount] = coords[(count - 1)];
    tempAltitudes[tempCoordsCount] = altitudes[(count - 1)];
    ++tempCoordsCount;

    RLMKMapWay* object =  [self polylineWithCoordinates:tempCoords altitudes:tempAltitudes count:tempCoordsCount];
    free(tempCoords);
    free(tempAltitudes);

    return object;
}

请注意,使用临时数据调用的polylineWithCoordinates方法负责复制所有数据,因此问题可能与调用后的空闲位置无关。我已尝试注释这两行,当count==1时,崩溃仍会发生,您正在分配的内存之外进行写入。

崩溃发生在哪一行?我有点困惑。。。CLLocationCoordinate2D不是一个结构吗?为什么要引用它的地址空间1和2?如何在不使用.location或.longitude的情况下访问它?此外,获取对象的大小需要类似于CLLocationCoordinate2D的指针,因为输入是CLLocationCoordinate2D的C样式数组。此外,sizeof的使用是正确的,因为CLLocationCoordinate2D的大小在编译时是已知的。。。这种验证是在更早的时候完成的。计数永远不会小于2。但你是对的。。。我应该在开头加一张支票!