From 55a76003b053ecaae94090bccb2a5b3b40f0c534 Mon Sep 17 00:00:00 2001 From: Maxim Biro Date: Wed, 13 Dec 2023 06:12:02 -0500 Subject: [PATCH] Replace memset(int32_t*, -1, _) with a for-loop memset() treats the passed buffer as a char* array, assigning to every 1-byte of the array the value. So for a single 4-byte int32_t element, it is assigning bytes 0, 1, 2 and 3 of it to -1. It happens that -1 is 0xFF, so in the end the uint32_t is set to 0xFFFFFFFF, which is -1 in the two's complement, so the memset() actually produces the correct result in the end, assuming the platform uses two's complement integers. Assigning it in the loop is less error-prone, as using memset() on non-1-byte wide arrays with a non-zero value is fishy, and it is more portable as we don't have to assume the use of two's complement. It looks like in a future version of the C standard, C23, two's complement is the only integer format in C23 (thanks to @robinlinden on IRC for pointing that out), so perhaps we shouldn't be as concerned with the portability here? Though @iphydf says that it's still a good idea to use a for-loop for this case. --- other/bootstrap_daemon/docker/tox-bootstrapd.sha256 | 2 +- toxcore/group_chats.c | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 b/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 index b281b2b9..ba9a4f46 100644 --- a/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 +++ b/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 @@ -1 +1 @@ -3c31e0cef0463b0a37bb21c5322c1a219314404b2a93193f4fba49f901a9dfb6 /usr/local/bin/tox-bootstrapd +92d0601d778487206505dce0bf89242b89b37424dc756808472fef3c22621ade /usr/local/bin/tox-bootstrapd diff --git a/toxcore/group_chats.c b/toxcore/group_chats.c index e7e7422f..39b8222b 100644 --- a/toxcore/group_chats.c +++ b/toxcore/group_chats.c @@ -7224,7 +7224,9 @@ static int get_new_group_index(GC_Session *c) c->chats[new_index] = empty_gc_chat; - memset(&c->chats[new_index].saved_invites, -1, sizeof(c->chats[new_index].saved_invites)); + for (size_t i = 0; i < sizeof(c->chats[new_index].saved_invites)/sizeof(*c->chats[new_index].saved_invites); ++i) { + c->chats[new_index].saved_invites[i] = -1; + } ++c->chats_index;