Skip to content

Commit

Permalink
Fix a bug in strncpy and add some tests that verify the behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
priettt committed Dec 28, 2024
1 parent e537269 commit d18c9a1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 6 deletions.
16 changes: 11 additions & 5 deletions embrace-android-sdk/src/main/cpp/utils/string_utils.c
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
#include "string_utils.h"
#include "../schema/stack_frames.h"

void emb_strncpy(char *dst, const char *src, size_t len) {
if (dst == NULL || src == NULL) {
/**
* Copy a string from source to destination. If the source is larger than the destination, it will be truncated.
* @param destination The destination buffer.
* @param source The source buffer.
* @param destination_len The length of the destination buffer.
*/
void emb_strncpy(char *destination, const char *source, size_t destination_len) {
if (destination == NULL || source == NULL) {
return;
}
int i = 0;
while (i <= len) {
char current = src[i];
dst[i] = current;
while (i < destination_len && source[i] != '\0') {
char current = source[i];
destination[i] = current;
if (current == '\0') {
break;
}
Expand Down
2 changes: 1 addition & 1 deletion embrace-android-sdk/src/main/cpp/utils/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
extern "C" {
#endif

void emb_strncpy(char *dst, const char *src, size_t len);
void emb_strncpy(char *destination, const char *source, size_t destination_len);
void emb_convert_to_hex_addr(uint64_t addr, char *buffer);

#ifdef __cplusplus
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,27 @@ TEST convert_to_hex(void) {
PASS();
}

TEST test_string_copy_larger_source(void) {
char dst[2];
char src[] = "123456";
emb_strncpy(dst, src, sizeof(dst));
ASSERT_STR_EQ("12", dst);
PASS();
}

TEST test_string_copy_larger_destination(void) {
char dst[6] = {0};
char src[] = "12";
emb_strncpy(dst, src, sizeof(dst));
ASSERT_STR_EQ("12", dst);
PASS();
}

SUITE(suite_utilities) {
RUN_TEST(string_copy_success);
RUN_TEST(string_null_src);
RUN_TEST(string_null_dst);
RUN_TEST(convert_to_hex);
RUN_TEST(test_string_copy_larger_source);
RUN_TEST(test_string_copy_larger_destination);
}

0 comments on commit d18c9a1

Please sign in to comment.