Skip to content

Integer overflow crash in Linux on FPSCounter.update #1

@DownloadableFox

Description

@DownloadableFox

Executing the simple "Hello World" example from the README.md page on Linux causes an instant crash after rendering the initial text. This is because FpsCounter.update is attempting to cache the time it took to generate 60 frames and constantly substracting and adding that time to the total_time variable.

// In animation.zig
pub fn update(self: *FpsCounter, delta_ms: u32) void {
    self.total_time -= self.frame_times[self.index];
    // ^ Integer underflow here! I am unsure of the causes.

    self.frame_times[self.index] = delta_ms;
    self.total_time += delta_ms;
    self.index = (self.index + 1) % 60;
}

In theory this shouldn't be a problem but for some reason on my machine running the latest version of Fedora the simple example program crashes instantly.

I've fixed it on my end by just calculating the total time rather than using a cashed value.

/// FPS counter
pub const FpsCounter = struct {
    frame_times: [60]u32 = undefined,
    index: usize = 0,

    pub fn init() FpsCounter {
        var f: FpsCounter = .{};
        f.index = 0;
        for (0..60) |i| {
            f.frame_times[i] = 16;
        }
        return f;
    }

    pub fn update(self: *FpsCounter, delta_ms: u32) void {
        self.frame_times[self.index] = delta_ms;
        self.index = (self.index + 1) % 60;
    }

    pub fn getFps(self: *FpsCounter) u32 {
        var total_time: u32 = 0;
        for (0..60) |i| {
            total_time += self.frame_times[i];
        }

        if (total_time == 0) return 0;
        const avg_ms: u32 = total_time / 60;
        if (avg_ms == 0) return 0;
        return 60000 / avg_ms;
    }
};

Of course, this doesn't solve why the issue is presented in the first place, as I don't see why it would crash when subtracting values that should have been added before.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions