sizeof(uint8_t) * sizeGenerally, this works OK, but I noticed something: what about overflow? If one of the values is too big, then the result will overflow and be completely wrong. The function thinks it's valid, and continues processing as usual. Eventually the program will crash because it tries to access outbounds. The function should be able to tell the program that it isn't possible to allocate such amount of memory.So, what I need is a way of checking for overflows. I've been looking around, and one suggestion seems to be to calculate the multiplication as floating comma first. If the value is larger than the limit, then overflow would happen. However, I don't know how much can floating comma values be trusted. Also there's the fact that it could be slow, although I can't come up with a better alternative speed-wise, and to be fair memory allocation is usually an initialization operation so it can afford to be sightly slower.
The other problem is that I need the values to be size_t, and there seems to be no standard way to determine that. If I recall correctly, the size in bits of size_t can be calculated as follows:
sizeof(size_t) * CHAR_BITBut then there's the issue of calculating the maximum value this type can hold! I know for sure that size_t is unsigned in my situation, but how do I calculate it safely? I came up with the following, and while it'll most likely work about everywhere, I'm not sure if this is the defined behaviour according to the standard:(1 << sizeof(size_t) * CHAR_BIT) - 1Any ideas on all this? (also: how many of you completely forgot about checking for overflows =P)