我碰到一些优化代码。我想要做的是当上一个和下一个点足够接近时,从输入数组中删除一些点。这种方法在几乎所有情况下都能很好地工作,但是会碰到一些特定数据崩溃EXC_BAD_ACCESS使用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
如果我跳过优化代码,并使用直接输入值,则一切正常。如果我只是在temp数组中memcpy输入值,它也能正常工作。
在发布输入数据后使用此方法后,我得到了一个EXC_BAD_ACCESS EXC_I386_GPFLT。崩溃不会直接发生在这个方法中,而是在我使用在方法结尾创建的对象之后。我已经尝试过NSZombie和Profiling for zombies。几乎所有的数据都能正常工作,但是这个特定的输入数据会崩溃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方法照顾使所有数据副本(我已经试着评论两条线,并且崩溃仍然发生)
哪条线是坠毁? – NobodyNada 2015-03-24 21:55:38
我有点困惑...不是'CLLocationCoordinate2D'结构?为什么你要引用它的地址空间(1)和(2)你如何在不使用.'location'或'.longitude'的情况下访问它?另外,获取对象的大小需要类似于http://stackoverflow.com/questions/761969/checking-the-size-of-an-object-in-objective-c – 2015-03-24 22:39:05
作为输入的CLLocationCoordinate2D指针是一个C风格的数组的CLLocationCoordinate2D。此外,sizeof的使用是正确的,因为CLLocationCoordinate2D的大小在编译时是已知的。 – olicarbo 2015-03-24 23:04:49