Here is simple C program which prints some addresses
    
    
    #include <stdio.h>
    #include <stdlib.h>
    
    struct thing {
        int a;
        int b;
    };
    
    int main(void)
    {
        struct thing t1, t2, *t3, *t4;
        printf(" t1 @ %p\n", &t1);
        printf(" t2 @ %p\n", &t2);
        printf(" t3 @ %p\n", &t3);
        printf(" t4 @ %p\n", &t4);
        
        t3 = calloc(1, sizeof(struct thing));
        t4 = calloc(1, sizeof(struct thing));
        
        printf("*t3 @ %p\n", t3);
        printf("*t4 @ %p\n", t4);
    }
    
    
    Run

Output:
    
    
     t1 @ 0x7ffcbecee138
     t2 @ 0x7ffcbecee140
     t3 @ 0x7ffcbecee128
     t4 @ 0x7ffcbecee130
    *t3 @ 0x56153fdc16b0
    *t4 @ 0x56153fdc16d0
    
    
    Run

>From the output I clearly see that all 4 variables are on the stack and `t3, 
>t4` points somewhere into the heap (addresses with lower values). Then I tried 
>to write something similar in Nim:
    
    
    from strutils import toHex, strip
    
    proc printAddr(p: pointer) =
      let u = cast[uint64](p)
      echo "0x", u.toHex.strip(leading = true, trailing = false, chars = {'0'})
    
    type
      Thing = object
        a: int
        b: int
    
    var
      t1 = Thing(a: 1, b: 2) # on the stack
      t2 = Thing(a: 3, b: 4) # on the stack
      t3, t4: ref Thing # on the heap
    
    printAddr(t1.addr)
    printAddr(t2.addr)
    
    t3 = new(Thing)
    t4 = new(Thing)
    echo t3.repr
    echo t4.repr
    
    
    Run

Output:
    
    
    0x55F7A66C3060
    0x55F7A66C3070
    ref 0x7f7e3c893050 --> [a = 0, b = 0]
    ref 0x7f7e3c893070 --> [a = 0, b = 0]
    
    
    Run

First two addresses seem to belong to the heap, aren't they? I expected them to 
be in the stack region. Second two other way around... If these are addresses 
of `t3, t4` (which are on the stack), then how to print locations where the 
objects seat? 

Reply via email to