I ran into a incredible frustrating issue where my compiler was seg faulting due to missing a ref in a type declaration. In the below code just swapping Node[T] = object to Node[T] = ref object stops the seg fault and compiles and runs as expected. In fact on MacOS I don't even get the segfault error, Segmentation fault (core dumped), instead the compiler just mysteriously stopped. The same thing happens with the devel branch I grabbed from choosenim.
type
Node[T] = object
item: T
next: Node[T]
Bag*[T] = ref object
first: Node[T]
size: int
You can reproduce the seg fault here: https://play.nim-lang.org/#ix=2u3O
Code from link:
import random
type
Node[T] = object
item: T
next: Node[T]
Bag*[T] = ref object
first: Node[T]
size: int
func isEmpty*(bag: Bag): bool =
bag.first == nil
func size*(bag: Bag): int =
bag.size
func add*[T](bag: Bag[T], item: T): void =
var oldFirst = bag.first
bag.first = new(Node[T])
bag.first.item = item
bag.first.next = oldFirst
bag.size += 1
var testBag = new(Bag[int])
for i in 1 .. 10:
randomize()
testBag.add(i * rand(100))
echo "Is the bag empty: " & $testBag.isEmpty
echo "Bag size: " & $testBag.size
Yeah, as @hugogranstrom mentioned, your Node definition is invalid - you can't have a type which has one of the fields of itself if it's not a ref object, because then you'll need an infinite amount of memory. So you should either do:
Node[T] = ref object
item: T
next: Node[T]
or (but that'll require you to write ref explicitly in prog arguments and whatnot):
Node[T] = object
item: T
next: ref Node[T]
I tried to compile the example with the recursive object and expected to get either a crash, as indicated, or a compiler error. But surprisingly, it compiles both with stable and development versions.
I declared a variable initialized specifying only the field item and it compiled. I added an echo to print the variable and I got nothing. The program simply terminates with no exception and no crash.
For sure, there’s something wrong here.
type
Node[T] = object
item: T
next: Node[T]
var x = Node[int](item:3)
echo x
… something is wrong with your compiler :P
No, i don’t think so :-). It’s likely a random error due to an access via some uninitialized pointer. And the executable I get after compilation seems to have a similar problem.