fix: correct buffer size in string subscript operator to prevent off-by-one allocation

The `string_subscript` native was allocating a 2-byte buffer for single-character
results, causing a one-byte over-allocation. Changed to allocate exactly 1 byte
for the character plus the null terminator handled by `wrenNewUninitializedString`.

Also fixed `wrenNewUninitializedString` to properly cast the `length` parameter
to `int` when assigning to `ObjString->length`, resolving a potential
truncation warning on 64-bit systems.

Added a test case to verify that subscript access returns a properly formed
string that compares equal to the expected character.
This commit is contained in:
Bob Nystrom
2015-01-09 15:12:25 +00:00
parent 0572df823b
commit f010c8d79f
3 changed files with 5 additions and 2 deletions
+1 -1
View File
@@ -968,7 +968,7 @@ DEF_NATIVE(string_subscript)
// The result is a one-character string.
// TODO: Handle UTF-8.
Value value = wrenNewUninitializedString(vm, 2);
Value value = wrenNewUninitializedString(vm, 1);
ObjString* result = AS_STRING(value);
result->value[0] = AS_CSTRING(args[0])[index];
result->value[1] = '\0';