What is the reason for reassigning the initialized pointer?

Viewed 42

I am currently learning c posix sockets. In the provided example https://www.man7.org/linux/man-pages/man3/getifaddrs.3.html the struct ifaddrs *ifaddr gets filled with all IP/interface/network info, using the 'getifaddrs(&ifaddr)' function. Then all info should be displayed by iterating through the ifaddr linked list.

In that context the ifaddr is assigned to a new ifa struct ifaddrs = ifaddr in the for (struct ifaddrs *ifa = ifaddr; ....) loop. What is the reason to make a new variable, instead of using the the already before initialized ifaddr to iterate through the list?

1 Answers

The original pointer populated via getifaddrs must be passed to freeifaddrs when it is no longer in use.

By using a separate pointer variable in the for loop, we retain the original value of ifaddr so it can be passed to freeifaddrs.

Related