bright yang
bright yang

Reputation: 99

Local variable is modified unintentially

When I pass (a,b) = (0,100) to this function, the variable sum is modified to 0 as if by magic. Im using Apple clang version 11.0.0 (clang-1100.0.33.8) Target: x86_64-apple-darwin18.7.0. and C++20. I wonder why and how?

int need_match(int a, int b){
    int sum = 4;
    char buf[3];
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "%d", a);
    for (int i = 0; i < 3; ++i) {
        if(buf[i]-'0' >= 0){
            sum += match_map[buf[i]-'0'];
        }
    }
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "%d", b);  // *** variable sum changes after this line ***
    for (int i = 0; i < 3; ++i) {
        if(buf[i]-'0' >= 0){
            sum += match_map[buf[i]-'0'];
        }
    }
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "%d", a+b);
    for (int i = 0; i < 3; ++i) {
        if(buf[i]-'0' >= 0){
            sum += match_map[buf[i]-'0'];
        }
    }
    return sum;
}

Upvotes: 0

Views: 90

Answers (1)

Caleth
Caleth

Reputation: 63402

the variable sum is modified to 0 as if by magic.

Your program has undefined behaviour, so variables magically changing is allowed.

sprintf requires that buf be at least as long as the string written, including the 0 terminator. When you pass 100, you need at least 4 characters in buf.

Upvotes: 2

Related Questions