Skip to content

Instantly share code, notes, and snippets.

@jbe
Last active August 29, 2015 13:58
Show Gist options
  • Save jbe/10099102 to your computer and use it in GitHub Desktop.
Save jbe/10099102 to your computer and use it in GitHub Desktop.
# The following code produces a segfault from within gc.nim (see bottom)
# The segfault does not occur when using --gc:markAndSweep
type
TNode = tuple
prev: ptr TNode
var
front = cast[ptr TNode](alloc0(sizeof(TNode)))
back = front
echo "allocated: " & $cast[int](front)
for i in 0..3:
back.prev = cast[ptr TNode](alloc0(sizeof(TNode)))
echo "allocated: " & $cast[int](back.prev)
back = back.prev
for i in 0..4:
var tmp = front
front = front.prev
echo "deallocating: " & $cast[int](tmp)
dealloc(tmp)
var str = cast[ptr string](alloc(sizeof(string)))
str[] = "hi" # SIGSEGV OCCURS ON THIS LINE (in gc.nim, see below)
#
# This is the result of running the program:
#allocated: -1220075480
#allocated: -1220075464
#allocated: -1220075448
#allocated: -1220075432
#allocated: -1220075416
#freed: -1220075480
#freed: -1220075464
#freed: -1220075448
#freed: -1220075432
#freed: -1220075416
#Traceback (most recent call last)
# testcase.nim(28) testcase
# gc.nim(269) unsureAsgnRef
# gc.nim(208) decRef
# gc.nim(121) canbeCycleRoot
# SIGSEGV: Illegal storage access. (Attempt to read from nil?)
@fowlmouth
Copy link

This error disappears when you use alloc0(sizeof(string)), I surmise that one of the ptr TNode is left on the stack and becomes the value given by alloc() just a guess though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment