#Statically allocated const pointers

1 messages · Page 1 of 1 (latest)

warm portal
#

What is the lifetime of statically allocated const pointers? i.e

const Int = struct {int: u8};

fn lifetimesWhatIThought() *const Int {
  //This is what I thought happened, but isn't what's happening.
  const x_data = Int{.int = 1};
  const x = &x_data;
  return x;
}

fn lifetimes() *const Int {
  const x: *const Int = &Int{.int = 1};
  // Obviously the elements live here
  return x;
}

pub main() void {
  const x = lifetimes();
  // The pointed to memory still live here, but where is the memory located?
}
heady quarry
#

the value is stored on the stack, and is invalid once lifetimes returns

#

what you thought is exactly what happens

cedar bane
#

dont temporary pointers like that live forever if the value is comptime known?

warm portal
#

I'm sorry, this question started as a genuine one but has now turned into a gripe with the std

#

And how the VTable is statically allocated in definitions. I think instead they should be put as consts in the struct

#
// line 302 in std.heap.GeneralPurposeAllocator
        pub fn allocator(self: *Self) Allocator {
            return .{
                .ptr = self,
                .vtable = &.{
                    .alloc = alloc,
                    .resize = resize,
                    .free = free,
                },
            };
        }
cedar bane
warm portal
#

Yes

jaunty mango
jaunty mango
dull estuary
#

static local variables are surprising

#

they are static though so the memory lives on as they are static variables I believe

warm portal
#

Is this really an instance of static locals? I mean it's not explicitly one at least

#

But I guess the

&.{//Comptime known struct
  ...
}

does that

dull estuary
#

It is also possible to have local variables with static lifetime by using containers inside functions.

#

is what the docs say

warm portal
#

Yes, but this doesn't really fit that example

dull estuary
#

ok maybe I'm confused because yours looks like it's in a container in a function

#

if it's more nuanced, maybe the docs need clarification

warm portal
#

In the example in the docs they explicitly create a statically known variable inside a struct. In my example, if one of the fields in vtable wasn't comptime known, or if the compiler for some reason didn't recognize the whole thing as comptime known, it would be created on the stack.

#

And fall out of scope as the function exited

#

Or that's at least my understanding of it all

dull estuary
#

which is not comptime known? sorry I'm learning still. This one? const x: *const Int = &Int{.int = 1};?

warm portal
#

I don't really know, haven't actually tested the code I wrote. My gripe is with the std code and where the vtable is created