#Is this safe to do, or a use after return bug?

1 messages · Page 1 of 1 (latest)

bold gust
#
const Iterator = struct {
    partition: *Self,

    // Window
    win_x: usize, // inclusive
    win_max_x: usize, // exclusive
    win_max_y: usize, // exclusive

    // State
    x: usize,
    y: usize,

    buffer: [32]*T = undefined,
    list: std.ArrayList(*T),

    pub fn init(self: *Self, win: ArrayWindow) Iterator {
        var result = Iterator{
            .partition = self,
            .win_x = win.x,
            .win_max_x = win.x + win.w,
            .win_max_y = win.y + win.h,
            .x = win.x,
            .y = win.y,
        };
        result.list = .initBuffer(&result.buffer);
        return result;
    }
}

I'm not sure what happens here with stack pointers, if this is invalid how could I change it so the list is properly initialized?

brave flint
#

There is no stack pointer in the snippet

bold gust
#

I'm talking about &result.buffer

brave flint
#

Wait, there is, im blind

#

Yeah, misread and thought it was part of self

bold gust
#

No worries

brave flint
#

Im not sure but i would guess that's unsafe because your buffer will exist but in another location (copy of the value being returned)

#

Also, declaring a type with one of its default values being undefined feels so wrong

bold gust
#

Lol yeah, I'm mainly just trying to init an array backed arraylist on the stack

#

not sure how I should be doing this

brave flint
#

I mean, having no values intialized, sure

#

But do it when creating an instance, explicitly, not in the type itself

bold gust
#

It's a specialized data type for my use case, I just want the backed array list to support 32 elements max

#

Does this seem incorrect, though? The arraylist init part

brave flint
#

Because you are "hiding" the fact that the array is not intialized

bold gust
#

like doing this?

result.buffer = undefined;
result.list = .initBuffer(&result.buffer);
#

err I guess in the iterator creation

brave flint
#

You could do it in the {}

bold gust
#

right

brave flint
#

And im of course missing a ton of context here, but i feel you dont need the arraylist, or is it going to grow past the initial size?

bold gust
#

I'm not sure this even compiles actually, with the arraylist not having a default

#

It's going to have a max of 32 elements

#

I could maybe just use the buffer itself manually

brave flint
brave flint
#

And if you really need an array list to interact with some library or the like, have a "method" that returns a wrapper for your inner array