有人可以解释为什么我的应用程序崩溃时出现以下错误:
EXC_BAD_ACCESS(代码= 1,地址= ...)
此崩溃仅发生在64位设备中。我无法理解。
- (NSString *)getIPAddress
{
NSString *address = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)// crashes here
{
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
{
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; // crash also here
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
谢谢!
答案 0 :(得分:1)
ifa_addr字段引用接口的地址或 的链接级别地址 接口,如果存在,否则为NULL。 (ifa_addr字段的sa_family字段应该是 咨询确定ifa_addr地址的格式。)
您的64位设备上可能没有填充ifa_addr
字段的接口。
要解决您的问题,请检查NULL ifa_addr
。我还建议您在找到en0
后完成后退出循环。
...
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr != NULL && temp_addr->ifa_addr->sa_family == AF_INET)
{
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
{
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
break;
}
}
temp_addr = temp_addr->ifa_next;
}
...