refactor: Factor out malloc+memcpy into memdup.

Only applied in one place, but perhaps later we can implement a pattern
in tokstyle to find more opportunities for using memdup.
This commit is contained in:
iphydf 2024-01-10 10:46:16 +00:00
parent 87bcc4322d
commit c4e209ea1d
No known key found for this signature in database
GPG Key ID: 3855DBA2D74403C9
4 changed files with 27 additions and 10 deletions

View File

@ -1 +1 @@
398b0a1ffe8d4d76252964636e083c18ee08e9ceab58b3b377b61821ca04c17c /usr/local/bin/tox-bootstrapd
10597d4f10d996d850e7f1b5237bcd5c9242d6c6d5ada6c6297fe484052f31fd /usr/local/bin/tox-bootstrapd

View File

@ -4076,17 +4076,11 @@ int gc_founder_set_password(GC_Chat *chat, const uint8_t *password, uint16_t pas
return -1;
}
uint8_t *oldpasswd = nullptr;
const uint16_t oldlen = chat->shared_state.password_length;
uint8_t *oldpasswd = memdup(chat->shared_state.password, oldlen);
if (oldlen > 0) {
oldpasswd = (uint8_t *)malloc(oldlen);
if (oldpasswd == nullptr) {
return -4;
}
memcpy(oldpasswd, chat->shared_state.password, oldlen);
if (oldpasswd == nullptr && oldlen > 0) {
return -4;
}
if (!set_gc_password_local(chat, password, password_length)) {

View File

@ -13,6 +13,7 @@
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include "ccompat.h"
@ -80,6 +81,21 @@ bool memeq(const uint8_t *a, size_t a_size, const uint8_t *b, size_t b_size)
return a_size == b_size && memcmp(a, b, a_size) == 0;
}
uint8_t *memdup(const uint8_t *data, size_t data_size)
{
if (data == nullptr || data_size == 0) {
return nullptr;
}
uint8_t *copy = (uint8_t *)malloc(data_size);
if (copy != nullptr) {
memcpy(copy, data, data_size);
}
return copy;
}
int16_t max_s16(int16_t a, int16_t b)
{
return a > b ? a : b;

View File

@ -41,6 +41,13 @@ non_null() int create_recursive_mutex(pthread_mutex_t *mutex);
*/
non_null() bool memeq(const uint8_t *a, size_t a_size, const uint8_t *b, size_t b_size);
/**
* @brief Copies a byte array of a given size into a newly allocated one.
*
* @return nullptr on allocation failure or if the input data was nullptr or data_size was 0.
*/
nullable(1) uint8_t *memdup(const uint8_t *data, size_t data_size);
// Safe min/max functions with specific types. This forces the conversion to the
// desired type before the comparison expression, giving the choice of
// conversion to the caller. Use these instead of inline comparisons or MIN/MAX