be more defensive when allocating and extending gap

This commit is contained in:
yrutschle 2021-08-24 20:07:28 +02:00
parent 4a6bbda60d
commit 1a3341c2a4
5 changed files with 12 additions and 10 deletions

View File

@ -30,8 +30,9 @@ struct cnx_collection {
gap_array* fd2cnx; /* Array indexed by file descriptor to things in cnx[] */
};
/* Allocates and initialises a new collection of connections. */
cnx_collection* collection_init(void)
/* Allocates and initialises a new collection of connections with at least
* `len` elements. */
cnx_collection* collection_init(int len)
{
cnx_collection* collection;
@ -40,7 +41,7 @@ cnx_collection* collection_init(void)
memset(collection, 0, sizeof(*collection));
collection->fd2cnx = gap_init();
collection->fd2cnx = gap_init(len);
return collection;
}

View File

@ -4,7 +4,7 @@
typedef struct cnx_collection cnx_collection;
cnx_collection* collection_init(void);
cnx_collection* collection_init(int len);
void collection_destroy(cnx_collection* collection);
struct connection* collection_alloc_cnx_from_fd(cnx_collection* collection, int fd);

7
gap.c
View File

@ -42,8 +42,8 @@ static int gap_len_alloc(int elem_size)
return getpagesize() / elem_size;
}
/* Creates a new gap, all pointers are initialised at NULL */
gap_array* gap_init(void)
/* Creates a new gap at least `len` big, all pointers are initialised at NULL */
gap_array* gap_init(int len)
{
gap_array* gap = malloc(sizeof(*gap));
if (!gap) return NULL;
@ -51,6 +51,7 @@ gap_array* gap_init(void)
int elem_size = sizeof(gap->array[0]);
gap->len = gap_len_alloc(elem_size);
if (gap->len < len) gap->len = len;
gap->array = malloc(gap->len * elem_size);
if (!gap->array) return NULL;
@ -85,7 +86,7 @@ static int gap_extend(gap_array* gap)
int gap_set(gap_array* gap, int index, void* ptr)
{
if (index >= gap->len) {
while (index >= gap->len) {
int res = gap_extend(gap);
if (res == -1) return -1;
}

2
gap.h
View File

@ -3,7 +3,7 @@
typedef struct gap_array gap_array;
gap_array* gap_init();
gap_array* gap_init(int len);
void* gap_get(gap_array* gap, int index);
int gap_set(gap_array* gap, int index, void* ptr);
void gap_destroy(gap_array* gap);

View File

@ -527,7 +527,7 @@ void main_loop(struct listen_endpoint listen_sockets[], int num_addr_listen)
fd_info.num_probing = 0;
FD_ZERO(&fd_info.fds_r);
FD_ZERO(&fd_info.fds_w);
fd_info.probing_list = gap_init();
fd_info.probing_list = gap_init(0);
for (i = 0; i < num_addr_listen; i++) {
FD_SET(listen_sockets[i].socketfd, &fd_info.fds_r);
@ -535,7 +535,7 @@ void main_loop(struct listen_endpoint listen_sockets[], int num_addr_listen)
}
fd_info.max_fd = listen_sockets[num_addr_listen-1].socketfd + 1;
fd_info.collection = collection_init();
fd_info.collection = collection_init(fd_info.max_fd);
while (1)
{