Let’s say n is an integer (an int variable in C). I need enough space for “4 times the ceiling of n divided by 3” bytes. How do I guarantee enough space for this?
Do you think malloc(4*(int)ceil(n/3.0)) will do, or do I have to add, say, 1 in order to be absolutely safe (due to possible rounding errors)?
An alternative to KerrekSB’s general formula which guarantees that only one division is used, is to calculate
(n+m-1)/m
To see that it produces the same, write
n = k*m + rwith0 <= r < m. Thenn%m == r, and ifr == 0, we haven+m-1 = k*m + (m-1)and(n+m-1)/m == k, otherwisen+m-1 = (k+1)*m + (r-1)and(n+m-1)/m == k+1.Most modern hardware gives you the quotient (
n/m) in one register and the remainder(n%m)in another when you do an integer division, so you can get both parts of Kerrek’s formula in one division, and most compilers will do so. If the compiler doesn’t, but uses two divisions, the calculation will be considerably slower, so if the computation is done often and performance is an issue, you can work around the compiler’s weakness with somewhat less obvious code.In the given case, the
mallocwould beBut since it’s not obvious to everyone what that formula does, if you use it, explain it in a comment, and if you don’t need to use it, use the more obvious code.