diff options
author | Ben Wiederhake <BenWiederhake.GitHub@gmx.de> | 2020-08-23 12:34:08 +0200 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-08-24 00:45:03 +0200 |
commit | 9795c61464413f876d2248271d1c074fe63df66d (patch) | |
tree | 719d21f1f7f8c5e593b13e3cef142f758536b440 | |
parent | 2adc3c61a218f28fe5d817f7cc7ae05e1a927931 (diff) | |
download | serenity-9795c61464413f876d2248271d1c074fe63df66d.zip |
LibC: Prevent slowness and overrun in strdup/strndup
strdup: Because the length is already known at the time of copying, there is
no need to use strcpy (which has to check every single byte, and thus tends
to be slower than memcpy).
strndup: If 'str' is not NUL-terminated, strndup used to run off into the
adjacent memory region. This can be fixed by using the proper strlen variant:
strnlen.
-rw-r--r-- | Libraries/LibC/string.cpp | 5 |
1 files changed, 3 insertions, 2 deletions
diff --git a/Libraries/LibC/string.cpp b/Libraries/LibC/string.cpp index cadd9669d6..4d25cd8fd2 100644 --- a/Libraries/LibC/string.cpp +++ b/Libraries/LibC/string.cpp @@ -94,13 +94,14 @@ char* strdup(const char* str) { size_t len = strlen(str); char* new_str = (char*)malloc(len + 1); - strcpy(new_str, str); + memcpy(new_str, str, len); + new_str[len] = '\0'; return new_str; } char* strndup(const char* str, size_t maxlen) { - size_t len = min(strlen(str), maxlen); + size_t len = strnlen(str, maxlen); char* new_str = (char*)malloc(len + 1); memcpy(new_str, str, len); new_str[len] = 0; |