Skip to content

Commit c436d4e

Browse files
committed
Merge pull request nodegit#454 from mattyclarkson/str-array-memory-fix
StrArray memory fix
2 parents 22430ec + 3e5cb89 commit c436d4e

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

generate/templates/manual/include/str_array_converter.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ class StrArrayConverter {
1616
private:
1717
static git_strarray *ConvertArray(Array *val);
1818
static git_strarray *ConvertString(Handle<String> val);
19+
static git_strarray *AllocStrArray(const size_t count);
1920
static git_strarray *ConstructStrArray(int argc, char** argv);
2021
};
2122

generate/templates/manual/src/str_array_converter.cc

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,17 @@ git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) {
2424
}
2525
}
2626

27+
static git_strarray * StrArrayConverter::AllocStrArray(const size_t count) {
28+
const size_t size = sizeof(git_strarray) + (sizeof(char*) * count);
29+
uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size));
30+
git_strarray *result = reinterpret_cast<git_strarray *>(memory);
31+
result->count = count;
32+
result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray));
33+
return result;
34+
}
35+
2736
git_strarray *StrArrayConverter::ConvertArray(Array *val) {
28-
git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray*));
29-
result->count = val->Length();
30-
result->strings = (char **)malloc(sizeof(char*) * result->count);
37+
git_strarray *result = AllocStrArray(val->Length());
3138

3239
for(size_t i = 0; i < result->count; i++) {
3340
NanUtf8String entry(val->Get(i));
@@ -47,9 +54,7 @@ git_strarray* StrArrayConverter::ConvertString(Handle<String> val) {
4754
}
4855

4956
git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) {
50-
git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray*));
51-
result->count = argc;
52-
result->strings = (char **)malloc(sizeof(char*) * result->count);
57+
git_strarray *result = AllocStrArray(argc);
5358

5459
for(size_t i = 0; i < result->count; i++) {
5560
result->strings[i] = strdup(argv[i]);

0 commit comments

Comments
 (0)