I was reading this book on my own , just for fun , and came across the following question :
This code has a security vulnerability ; Can you find and fix it? :
bool isValidAddition(unsigned short x, unsigned short y)
{
if(x + y < x)
return false;
else
return true;
}
Can someone help me , recognize the vulnerability ?
We know that the following points are true as per the C Standard
:
- sizeof(short) <= sizeof(int) <= sizeof(long)
- sizeof(short) >= 2 bytes , sizeof(int) >= 2 bytes, sizeof(long) >= 4 bytes
- There is an implicit integer promotion of operand data types used in arithmetic expressions which is done by the compiler
So in the code snippet above do the following :
Change
if(x + y < x)
to
if((unsigned short)(x + y) < x)
This will worrk if int is 4 (or >2) bytes
Hope this helps :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.