在此先感謝所有試圖幫助我的人。我在這裏遇到了一個大問題,我找到了一些關於sysctl的示例代碼並對其進行了擴展,以便我可以查詢網絡接口的輸入/輸出數據。當我直接在main()(沒有任何NSAutoreleasePool)中運行這段代碼時,一切正常。但是,一旦我將它添加到我的課程並執行它,我會遇到總線錯誤& segfaults。我已經將問題追蹤到NSAutoreleasePools。任何人都可以幫忙嗎? (如果你不相信它,只需將一個NSAutoreleasePool *池= [[NSAutoreleasePool的alloc]初始化]代碼之前,並把整個事情到主())sysctl在NSAutoreleasePool - > bus errors&segfaults
int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0 };
int alloc;
struct if_msghdr *ifm, *nextifm;
struct sockaddr_dl *sdl;
char *lim, *next;
size_t needed;
char s[32];
char* buf;
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
return 0;
if (alloc < needed) {
buf = malloc(needed);
if (buf == NULL)
return 0;
alloc = needed;
}
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
return 0;
lim = buf + needed;
next = buf;
while (next < lim) {
ifm = (struct if_msghdr *)next;
if (ifm->ifm_type != RTM_IFINFO)
return 0;
next += ifm->ifm_msglen;
while (next < lim) {
nextifm = (struct if_msghdr *)next;
if (nextifm->ifm_type != RTM_NEWADDR)
break;
next += nextifm->ifm_msglen;
}
if (ifm != NULL && ifm->ifm_flags & IFF_UP) {
sdl = (struct sockaddr_dl *)(ifm + 1);
if (sdl->sdl_family != AF_LINK)
continue;
strncpy(s, sdl->sdl_data, sdl->sdl_nlen);
s[sdl->sdl_nlen] = '\0';
NSLog(@"interface %s in %qu out %qu \n", s,(UInt64)ifm->ifm_data.ifi_ibytes, (UInt64)ifm->ifm_data.ifi_obytes);
}
}
你是完全正確的。這是因爲我沒有初始化int alloc。 – YllierDev 2011-03-27 20:15:17
這就是爲什麼初始化所有變量作爲一種習慣是個好主意。例如,如果buf初始化爲NULL,則會更容易找到alloc的缺失初始化,因爲崩潰早就發生了。 – smorgan 2011-03-27 20:16:38