我正在通過關注Beej's Guide to Network Programming文章學習網絡編程。有一個例子:在freeaddrinfo上發生了什麼事?
bind()
struct addrinfo hints, *servinfo, *p;
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
//socket(...)
//bind(...)
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
後,freeaddrinfo()
被調用。我認爲servinfo
鏈接列表現在應爲NULL,並且指針p
應該爲NULL,但不是,p
不是NULL,代碼運行良好。
我想知道爲什麼在調用freeaddrinfo
之後p
不爲空?
是的!是的!指針仍然是指針。即使'* p'也是空的。謝謝! – user1418404
調用'freeaddrinfo()'後''p'不保證爲NULL。如果'* p'變爲NULL',那麼分配內存管理器的副作用就是釋放'serveinfo'。有些內存管理器在釋放內存時會將內存清零(或者甚至用特殊的值如0xcdcdcdcd或0xbaadfood來幫助調試),但是不能依賴代碼中的行爲。 –