Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stb_sprintf: fix overflow in negating INT_MIN #1725

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

hjbreg
Copy link

@hjbreg hjbreg commented Dec 6, 2024

stbsp_sprintf failed for INT_MIN with %d. I found that there is a negative operation on signed integer may lead to overflow.

According to C11.6.2.6.9, I fixed this bug by negating unsigned integer.

#include <assert.h>
#include <limits.h>

#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"

int main()
{
    int n = 0;
    char buf[64];
    n = stbsp_sprintf(buf, "%d", INT_MIN + 1);
    assert(n == 11);
    n = stbsp_sprintf(buf, "%d", INT_MIN);
    assert(n == 11);
    return 0;
}

gcc -std=c11 -O2 a.c && ./a.out

a.out: a.c:14: main: Assertion `n == 11' failed.
Aborted (core dumped)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant