There's a couple things wrong with this code. But let's start with the wrong 
assumption(s) that led you to try this in the first place.

> I've realized that storing the entire object requires a lot of memory

Your object is the size of an integer, so it is exactly the same size as a 
pointer. Of course if you add more fields this will add up, but you need to 
store the data in your object somewhere, often just having it in a table is the 
right choice. But let's say your object actually is massive, and you want to 
avoid copies. The object you've got there is also a `ref object`, this means 
that when you create it, it is allocated on the heap, and whenever you pass the 
object around you're actually just passing around a pointer. It will be 
automatically freed once the last reference to it goes out of scope, and you 
can basically just relax. So having `Table[string, myObj]` would actually just 
store pointers already, no more fuzz! If you need to pass a `ref object` to a C 
function you can use `addr` to tell Nim to give you the pointer instead of 
abstracting it away, just keep in mind that the reference needs to stay in 
scope as long as the C code wants to access it.

With that said, let's have a look at your code. The problem here is pretty much 
the exact thing I warned against, you create a `myObj` as a local variable in 
your function, then you manually store a pointer to it in the table, 
circumventing Nims reference counting, then you return. As you return from this 
function Nim sees that `myObj` goes out of scope, and since you just 
circumventing the reference counting that's the only reference Nim knows about. 
So Nim diligently frees your object since you're no longer using it. Once you 
try to use it later on it isn't actually a `nil` dereference issue, but rather 
a user after free issue. Putting the contents of `initTableObj` into 
`callTableObj` just means that the local variable doesn't have time to go out 
of scope before you try to use it, and as such Nim hasn't gotten around to free 
it yet.

Hopefully that helps, and welcome to the Nim community!

Reply via email to