Skip to content

Commit

Permalink
Merge pull request #45 from wukgdu/fix-calculator
Browse files Browse the repository at this point in the history
fix memory leak in calculator example
  • Loading branch information
zenith391 committed Jun 17, 2023
2 parents 7c8accd + 68bbc0f commit b6ee15c
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions examples/calculator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn pressedKey(button_: *anyopaque) !void {
const labelText = computationLabel.getText();

// Concat the computation label with the first character of the button's label
var larger = try allocator.allocSentinel(u8, labelText.len + 1, 0); // allocate a null-terminated string one character longer than labelText
var larger = try allocator.alloc(u8, labelText.len + 1); // allocate a string one character longer than labelText
std.mem.copy(u8, larger, labelText); // copy labelText's contents to the newly allocated string
larger[labelText.len] = buttonLabel[0]; // finally, set the last letter

Expand All @@ -31,6 +31,7 @@ pub fn pressedKey(button_: *anyopaque) !void {

// TODO: switch back to *capy.Button_Impl when ziglang/zig#12325 is fixed
pub fn erase(_: *anyopaque) !void {
allocator.free(computationLabel.getText());
computationLabel.setText("");
}

Expand Down Expand Up @@ -76,9 +77,9 @@ pub fn compute(_: *anyopaque) !void {
}
}

const text = try std.fmt.allocPrintZ(allocator, "{d}", .{result});
allocator.free(computationLabel.getText());
const text = try std.fmt.allocPrint(allocator, "{d}", .{result});
computationLabel.setText(text);
allocator.free(text);
}

pub fn main() !void {
Expand All @@ -96,6 +97,7 @@ pub fn main() !void {

var window = try capy.Window.init();
computationLabel = capy.Label(.{ .text = "", .alignment = .Left });
defer allocator.free(computationLabel.getText());
try window.set(capy.Column(.{ .expand = .Fill, .spacing = 10 }, .{
&computationLabel,
Expanded(Row(.{ .expand = .Fill, .spacing = 10 }, .{
Expand Down

0 comments on commit b6ee15c

Please sign in to comment.