Home > other >  C : why local variable is modifying with sprintf?
C : why local variable is modifying with sprintf?

Time:02-16

consider this example. I created a local scoped buffer below which can store 2 characters and one terminator. But when I cross that thresold with 2 digits number i.e a = 20 then something weird happens when I call sprintf. a gets modified and prints out 0. If I change buff size from 3 to 4. variable a doesn't change. what is this frustrating behaviour? I am using clang 13.0.0 compiler.

int main(int argc, const char * argv[]) {
    
  
    int a = 20;
    {
        char buff[3];
        sprintf(buff, "a%d", a);
    }
    printf("value of a %d",a);
    
    return 0;
}

Thanks.

CodePudding user response:

You have corrupted the buffer. So it will result a Undefined Behaviour.

The size of memory pointed by buff is only 3 bytes. sprintf(buff, "a%d", a); writes 4 bytes to it. Because a is also on the stack, it gets being corrupted.

  • Related