From 427ba8ec40c283e09b966ae066197a83a68a53fd Mon Sep 17 00:00:00 2001 From: olehougaard Date: Wed, 18 Mar 2009 12:27:37 +0000 Subject: [PATCH] Introducing a new StrNDup function that uses new[] for when we dispose the result using delete[]. Review URL: http://codereview.chromium.org/48127 git-svn-id: http://v8.googlecode.com/svn/branches/bleeding_edge@1532 ce2b1a6d-e550-0410-aec6-3dcde31c8c00 --- src/allocation.cc | 10 ++++++++++ src/allocation.h | 7 ++++--- src/d8-readline.cc | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/allocation.cc b/src/allocation.cc index d7d21aaa6..3d26123bf 100644 --- a/src/allocation.cc +++ b/src/allocation.cc @@ -87,6 +87,16 @@ char* StrDup(const char* str) { } +char* StrNDup(const char* str, size_t n) { + size_t length = strlen(str); + if (n < length) length = n; + char* result = NewArray(length + 1); + memcpy(result, str, length * kCharSize); + result[length] = '\0'; + return result; +} + + int NativeAllocationChecker::allocation_disallowed_ = 0; diff --git a/src/allocation.h b/src/allocation.h index 35e68bde0..a690f0835 100644 --- a/src/allocation.h +++ b/src/allocation.h @@ -119,10 +119,11 @@ static void DeleteArray(T* array) { } -// The normal strdup function uses malloc. This version of StrDup -// uses new and calls the FatalProcessOutOfMemory handler if -// allocation fails. +// The normal strdup functions use malloc. These versions of StrDup +// and StrNDup uses new and calls the FatalProcessOutOfMemory handler +// if allocation fails. char* StrDup(const char* str); +char* StrNDup(const char* str, size_t n); // Allocation policy for allocating in the C free store using malloc diff --git a/src/d8-readline.cc b/src/d8-readline.cc index b86648d00..34b7b60df 100644 --- a/src/d8-readline.cc +++ b/src/d8-readline.cc @@ -103,7 +103,7 @@ char* ReadLineEditor::CompletionGenerator(const char* text, int state) { static unsigned current_index; static Persistent current_completions; if (state == 0) { - i::SmartPointer full_text(i::OS::StrNDup(rl_line_buffer, rl_point)); + i::SmartPointer full_text(i::StrNDup(rl_line_buffer, rl_point)); HandleScope scope; Handle completions = Shell::GetCompletions(String::New(text), String::New(*full_text)); -- 2.34.1