Skip to content

Compiler Seg faulting when using "object" instead of "ref object" for nested object #15186

Open
@davidbruce

Description

@davidbruce

Originally from: https://forum.nim-lang.org/t/6679

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

Example

You can reproduce the seg fault here: https://play.nim-lang.org/#ix=2u3O

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

Current Output

Segmentation fault (core dumped)

Expected Output

An error of some kind pointing out the need for a reference.

Nim Compiler Version 1.0 and beyond

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions