#Strange behavior

1 messages · Page 1 of 1 (latest)

nova quarry
#

I have a struct named Http.

pub const Http = struct {
    client: *Client,
    allocator: Allocator,
    const Self = @This();

    pub fn init(allocator: Allocator) Http {
        return Self{
            .client = &Client{ .allocator = allocator },
            .allocator = allocator,
        };
    }
    pub fn deinit(self: *Self) void {
        self.client.deinit();
    }
}

And write a test but it is failed.
error message :|| Test [1/1] test.init http... Illegal instruction at address 0x7ff80370ff3a

test "init http" {
    var allocator = std.testing.allocator;
    var http: Http = Http.init(allocator);
    defer http.deinit();
}

According to debugger, it is wired that the ptr of client's allocator is changed in the "defer http.deinit()".

But change the test and it works.

 var allocator = std.testing.allocator;
 var http: Http = Http{ .allocator = allocator, .client = &Client{ .allocator = allocator } };
defer http.deinit();

Here the ptr of client's allocator is not changed in the "defer http.deinit()".
Is it caused by the defer or something else.

safe adder
#

.client = &Client{ .allocator = allocator }, returns a pointer to a temporary variable allocated on the stack, once init returns, stack memory is freed and this pointer is garbage

#

you need to either (a) not use a pointer, store the Client in the struct directly, or (b) allocate space for the client and then initialize it there