Skip to content

Commit

Permalink
Fixed issue with strndup on Windows
Browse files Browse the repository at this point in the history
Ticket: None
Changelog: None
Signed-off-by: Lars Erik Wik <[email protected]>
  • Loading branch information
larsewi committed May 2, 2024
1 parent a92b252 commit b00e2ed
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
27 changes: 24 additions & 3 deletions lib/string_lib.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ LCH_List *LCH_StringSplit(const char *str, const char *del) {
const char *end = strpbrk(str, del);

while (end != NULL) {
char *tmp = strndup(start, end - start);
char *tmp = LCH_StringNDuplicate(start, end - start);
if (tmp == NULL) {
LCH_LOG_ERROR("strndup(3): Failed to allocate memory: %s",
strerror(errno));
return NULL;
}

Expand Down Expand Up @@ -293,3 +291,26 @@ char *LCH_StringDuplicate(const char *const str) {
}
return dup;
}

char *LCH_StringNDuplicate(const char *const str, const size_t n) {
if (str == NULL) {
return NULL;
}

#if HAVE_STRNDUP
char *const dup = strndup(str, n);
if (dup == NULL) {
LCH_LOG_ERROR("strndup(3): Failed to allocate memory: %s", strerror(errno));
return NULL;
}
#else // HAVE_STRNDUP
char *const dup = malloc(n + 1);
if (dup == NULL) {
LCH_LOG_ERROR("malloc(3): Failed to allocate memory: %s", strerror(errno));
return NULL;
}
memcpy(dup, str, n);
dup[n] = '\0';
#endif // HAVE_STRNDUP
return dup;
}
2 changes: 2 additions & 0 deletions lib/string_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ char *LCH_StringTruncate(const char *str, size_t len, size_t max);

char *LCH_StringDuplicate(const char *str);

char *LCH_StringNDuplicate(const char *str, size_t n);

char *LCH_StringFormat(const char *format, ...);

bool LCH_StringParseNumber(const char *str, long *number);
Expand Down
5 changes: 3 additions & 2 deletions tests/check_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#endif // _WIN32

#include "../lib/buffer.h"
#include "../lib/string_lib.h"

START_TEST(test_LCH_Buffer) {
LCH_Buffer *buffer = LCH_BufferCreate();
Expand Down Expand Up @@ -141,7 +142,7 @@ START_TEST(test_LCH_BufferAllocate2) {
length = ntohl(*len_ptr);
offset += sizeof(uint32_t);

char *str = strndup(LCH_BufferData(buffer) + offset, length);
char *str = LCH_StringNDuplicate(LCH_BufferData(buffer) + offset, length);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "beatles");
offset += length;
Expand All @@ -153,7 +154,7 @@ START_TEST(test_LCH_BufferAllocate2) {
length = ntohl(*len_ptr);
offset += sizeof(uint32_t);

str = strndup(LCH_BufferData(buffer) + offset, length);
str = LCH_StringNDuplicate(LCH_BufferData(buffer) + offset, length);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "pinkfloyd");
offset += length;
Expand Down

0 comments on commit b00e2ed

Please sign in to comment.