mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 08:54:53 +00:00
fixes #24664 ```nim proc main() = for i in 0..1: var s = "12345" s.add s echo s main() ``` In the given example, `add` contains two steps: `prepareAdd` and `appendString`. In the first step, a new buffer is created in order to store the final doubled string. But it doesn't copy the null terminator, neither zeromem the left unused spaces. It causes a problem because `appendString` will copy itself which doesn't end with `\0` properly so contaminated memory is copied instead. ``` var s = 12345\0 prepareAdd: var s = 12345xxxxx\0 appendString: var s = 1234512345x ```
This commit is contained in:
@@ -112,9 +112,10 @@ proc nimToCStringConv(s: NimStringV2): cstring {.compilerproc, nonReloadable, in
|
||||
|
||||
proc appendString(dest: var NimStringV2; src: NimStringV2) {.compilerproc, inline.} =
|
||||
if src.len > 0:
|
||||
# also copy the \0 terminator:
|
||||
copyMem(unsafeAddr dest.p.data[dest.len], unsafeAddr src.p.data[0], src.len+1)
|
||||
# don't copy the \0 terminator:
|
||||
copyMem(unsafeAddr dest.p.data[dest.len], unsafeAddr src.p.data[0], src.len)
|
||||
inc dest.len, src.len
|
||||
dest.p.data[dest.len] = '\0'
|
||||
|
||||
proc appendChar(dest: var NimStringV2; c: char) {.compilerproc, inline.} =
|
||||
dest.p.data[dest.len] = c
|
||||
|
||||
14
tests/system/t24664.nim
Normal file
14
tests/system/t24664.nim
Normal file
@@ -0,0 +1,14 @@
|
||||
discard """
|
||||
output: '''
|
||||
TestString123TestString123
|
||||
TestString123TestString123
|
||||
'''
|
||||
"""
|
||||
|
||||
proc foostring() = # bug #24664
|
||||
for i in 0..1:
|
||||
var s = "TestString123"
|
||||
s.add s
|
||||
echo s
|
||||
|
||||
foostring()
|
||||
Reference in New Issue
Block a user