I have been fixing several issues last few weeks, and the following issue in someone's code is a clear test for understanding differences between strings and char's.
On the first look "%s%c" and "%s%1s" seem very similar, but unfortunately NO! and they can create some nasty runtime bugs corrupting your variables, suppose the code existing in someone's code like this.
void BuggyScanner(){
char buf[MAX_SIZE];
int a;
char b;
scanf("%d",&a);
scanf("%3s%1s",buf,&b);
printf("a=%d buf=%s b=%c\n",a,buf,b);
}
The format specifier is really a blunder as scanf "%1s" is going to write
beyond one byte (the extra '\0' which gets padded for strings)at the
address of 'b' , since 'buf','a','b' are on the stack writing one byte
beyond the address of 'b' can do really nasty stuff.
- Just as in this corrupted the variables.
- Potentially corrupt the return address of the function, creating a great security bug.
1 comment:
Post a Comment