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?

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

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 🙂