Skip to content

Commit 5f11635

Browse files
committedApr 3, 2017
multi: make curl_multi_wait avoid malloc in the typical case
When only a few additional file descriptors are used, avoid the malloc. Closes #1377
1 parent 55f4aba commit 5f11635

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed
 

‎lib/multi.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -974,6 +974,8 @@ CURLMcode curl_multi_fdset(struct Curl_multi *multi,
974974
return CURLM_OK;
975975
}
976976

977+
#define NUM_POLLS_ON_STACK 10
978+
977979
CURLMcode curl_multi_wait(struct Curl_multi *multi,
978980
struct curl_waitfd extra_fds[],
979981
unsigned int extra_nfds,
@@ -987,8 +989,10 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
987989
unsigned int nfds = 0;
988990
unsigned int curlfds;
989991
struct pollfd *ufds = NULL;
992+
bool ufds_malloc = FALSE;
990993
long timeout_internal;
991994
int retcode = 0;
995+
struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
Code has comments. Press enter to view.
992996

993997
if(!GOOD_MULTI_HANDLE(multi))
994998
return CURLM_BAD_HANDLE;
@@ -1028,9 +1032,14 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
10281032
nfds += extra_nfds; /* add the externally provided ones */
10291033

10301034
if(nfds || extra_nfds) {
1031-
ufds = malloc(nfds * sizeof(struct pollfd));
1032-
if(!ufds)
1033-
return CURLM_OUT_OF_MEMORY;
1035+
if(nfds > NUM_POLLS_ON_STACK) {
1036+
ufds = malloc(nfds * sizeof(struct pollfd));
1037+
if(!ufds)
1038+
return CURLM_OUT_OF_MEMORY;
1039+
ufds_malloc = TRUE;
1040+
}
1041+
else
1042+
ufds = &a_few_on_stack[0];
10341043
}
10351044
nfds = 0;
10361045

@@ -1108,7 +1117,8 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
11081117
}
11091118
}
11101119

1111-
free(ufds);
1120+
if(ufds_malloc)
1121+
free(ufds);
11121122
if(ret)
11131123
*ret = retcode;
11141124
return CURLM_OK;

0 commit comments

Comments
 (0)
Please sign in to comment.