What are arithmetic checks? Why should I avoid using them with memcpy and other unsafe functions?

Developers sometimes attempt to make unsafe functions safe by adding in their own checks.

int len = packet.getlen();
char* buf = new char[1000];
if(len*4 > 1000){
return 1;
}else{
memcpy(buf, packet.getbuf(), len*4);
}

While these arithmetic checks usually work, sometimes they are incorrect by accident, or due to misunderstanding of integer or compiler optimization behavior. It is better to use the well-tested checks built into safe string and memory handling functions.

Can you find the error in the code above?

3 responses to What are arithmetic checks? Why should I avoid using them with memcpy and other unsafe functions?


Leave a Reply

Your email address will not be published.