From: Lars-Peter Clausen Date: Sat, 30 Jun 2012 18:54:42 +0000 (+0200) Subject: sr: session: Use realloc to resize source array X-Git-Tag: dsupstream~878 X-Git-Url: http://sigrok.org/gitweb/?p=libsigrok.git;a=commitdiff_plain;h=2bccd322bc40a2ebe41a9d3f1c4b12cd52cb2595 sr: session: Use realloc to resize source array Use realloc to resize the source array when adding or removing a source. This makes the code a bit smaller. In the remove function we now check whether the fd is valid before doing anything else and if it is not simply do nothing. If it is valid use memove to move the elements following the source one element down in the array. Only after that has been done the array is re-allocated. Signed-off-by: Lars-Peter Clausen --- diff --git a/session.c b/session.c index 89ea5ad4..2dc3c43c 100644 --- a/session.c +++ b/session.c @@ -505,18 +505,12 @@ SR_API int sr_session_source_add(int fd, int events, int timeout, /* Note: cb_data can be NULL, that's not a bug. */ - new_sources = g_try_malloc0(sizeof(struct source) * (num_sources + 1)); + new_sources = g_try_realloc(sources, sizeof(struct source) * (num_sources + 1)); if (!new_sources) { sr_err("session: %s: new_sources malloc failed", __func__); return SR_ERR_MALLOC; } - if (sources) { - memcpy(new_sources, sources, - sizeof(struct source) * num_sources); - g_free(sources); - } - s = &new_sources[num_sources++]; s->fd = fd; s->events = events; @@ -553,28 +547,29 @@ SR_API int sr_session_source_remove(int fd) return SR_ERR_BUG; } - /* TODO: Check if 'fd' valid. */ - - new_sources = g_try_malloc0(sizeof(struct source) * num_sources); - if (!new_sources) { - sr_err("session: %s: new_sources malloc failed", __func__); - return SR_ERR_MALLOC; + for (old = 0; old < num_sources; old++) { + if (sources[old].fd == fd) + break; } - for (old = 0, new = 0; old < num_sources; old++) { - if (sources[old].fd != fd) - memcpy(&new_sources[new++], &sources[old], - sizeof(struct source)); + /* fd not found, nothing to do */ + if (old == num_sources) + return SR_OK; + + num_sources -= 1; + + if (old != num_sources) { + memmove(&sources[old], &sources[old+1], + (num_sources - old) * sizeof(struct source)); } - if (old != new) { - g_free(sources); - sources = new_sources; - num_sources--; - } else { - /* Target fd was not found. */ - g_free(new_sources); + new_sources = g_try_realloc(sources, sizeof(struct source) * (num_sources - 1)); + if (!new_sources && num_sources > 0) { + sr_err("session: %s: new_sources malloc failed", __func__); + return SR_ERR_MALLOC; } + sources = new_sources; + return SR_OK; }