-2

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.

  • Overflowing buffers results in Undefined Behaviour. C doesn't stop you from doing that and anything after that point is undefined. So it's your job as a programmer to ensure that doesn't occur. – kaylum Feb 16 '22 at 06:05
  • 1
    Have a look to snprintf. – Emmanuel DUMAS Feb 16 '22 at 06:29

1 Answers1

2

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

The size of the buffer 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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Zongru Zhan
  • 546
  • 2
  • 8