#Segfault when attempting to free a slice inside a struct

1 messages · Page 1 of 1 (latest)

open tinsel
#

I have the following struct:

pub const MyStruct = struct {
    allocator: Allocator,
    count: u16,
    code: []u8,
};

This is the function I use to create it:

pub fn initMyStruct(allocator: Allocator) !*MyStruct{
    const code = try allocator.alloc(u8, 8);
    var result = MyStruct{
        .allocator = allocator,
        .count = 0,
        .code = code,
    };

    return &result;
}

Here's how I'm trying to destroy it (doesn't work):

pub fn freeMyStruct(my_struct: *MyStruct) void {
    var allocator = my_struct.allocator;
    freeArray(MyStruct, allocator, chunk.code);
}

pub fn freeArray(comptime T: type, allocator: Allocator, pointer: []T) void {
    allocator.free(pointer);
}

I get a segfault when trying to free the slice. What am I doing wrong?

sage owl
#

you're returning a pointer to memory that doesn't exist

#

not the stuff you're allocating, but when you return &result

#

because you make result on the stack, it doesn't necessarily exist outside of that initMyStruct function

#

you probably want to return a MyStruct value rather than a pointer to MyStruct

#

also i'm not sure where the chunk.code bit is coming from, i'm assuming that's some global thing?

#

the typical zig way to do this would be to have everything in a single struct, looking something like this:

pub const MyStruct = struct{
  allocator: Allocator, 
  count: u16,
  code: []u8,

  pub fn init(allocator: Allocator)!MyStruct{
    return MyStruct{
      .allocator = allocator, 
      .count = 0,
      .code = try allocator.alloc(u8, 8),
    };
  }

  pub fn deinit(self: MyStruct){
    self.allocator.free(code);
  }
};
open tinsel
#

Thank you very much!