Skip to content

Commit 8d78d5b

Browse files
committed
fix example to not potentially have undefined behavior
1 parent 49a72e6 commit 8d78d5b

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

docs.md

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,11 @@ void process(dnsstate_t *state)
177177
struct timeval tv;
178178

179179
while (1) {
180-
int rv;
181-
int timeout;
182-
size_t i;
180+
int rv;
181+
int timeout;
182+
size_t i;
183+
struct pollfd *fds;
184+
size_t nfds;
183185

184186
/* Since we don't have any other program state to wait on, we'll just
185187
* stop looping when we know there are no remaining queries, which is
@@ -199,18 +201,24 @@ void process(dnsstate_t *state)
199201
continue;
200202
}
201203

202-
for (i=0; i<state->nfds; i++) {
203-
if (state->fds[i].revents == 0) {
204+
/* Duplicate fds structure as calling into ares_process_fd() may manipulate
205+
* the one contained in state */
206+
nfds = state->nfds;
207+
fds = malloc(sizeof(*fds) * nfds);
208+
memcpy(fds, state->fds, sizeof(*fds) * nfds);
209+
210+
for (i=0; i<nfds; i++) {
211+
if (fds[i].revents == 0) {
204212
continue;
205213
}
206214

207215
/* Notify about read/write events per FD */
208216
ares_process_fd(state->channel,
209-
(state->fds[i].revents & (POLLERR|POLLHUP|POLLIN))?
210-
state->fds[i].fd:ARES_SOCKET_BAD,
211-
(state->fds[i].revents & POLLOUT)?
212-
state->fds[i].fd:ARES_SOCKET_BAD);
217+
(fds[i].revents & (POLLERR|POLLHUP|POLLIN))?fds[i].fd:ARES_SOCKET_BAD,
218+
(fds[i].revents & POLLOUT)?fds[i].fd:ARES_SOCKET_BAD);
213219
}
220+
221+
free(fds);
214222
}
215223
}
216224

0 commit comments

Comments
 (0)