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?


  1. atkarapa

    I see many potential errors but it all depends on the compiler and the targeted platform.
    1. 4*len might wraparound if 4*len > INT_MAX
    2. Also in the case when len is 0 this will cause undefined behavior.
    3. packet.getbuf() might be null so it must be checked as well

    I am really curious what else might be wrong

  2. Natalie Silvanovich

    1 was the intended problem. I don’t think 2 is a problem, new has the defined behaviour of allocating an empty when called on 0. It’s possible that this would cause problems in later code, but not necessarily, depending on what it does. 3 could also be a problem, but not the one I was thinking of 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *