The _Bool type in C99 (typedef'ed to bool in stdbool.h) doesn't have a standard defined size, but according to section 6.2.5 of the C99 Standard:
2 An object declared as type _Bool is large enough to store the values 0 and 1.
In C, the smallest addressable object (aside from bitfields) is the char, which is at least 8-bits wide, and sizeof(char) is always 1.
_Bool and bool therefore have a sizeof of at least 1, and in most implementations that I've seen, sizeof(bool) / sizeof(_Bool) is 1.
If you take a look at GCC's stdbool.h, you'll get this:
#define bool _Bool
#if __STDC_VERSION__ < 199901L && __GNUC__ < 3
typedef int _Bool;
#endif
#define false 0
#define true 1
So if using an older version of GCC and an old version of the C standard when compiling, you will use int as a _Bool type.
Of course, as an interesting thing, check this out:
#include <stdio.h>
#include <stdbool.h>
int main() {
printf("%zu\n", sizeof(_Bool));
printf("%zu\n", sizeof(true));
printf("%zu\n", sizeof(false));
}
Output:
λ > ./a.out
1
4
4
GCC 4.2.4, Clang 3.0, and GCC 4.7.0 all output the same. As trinithis points out, sizeof(true) and sizeof(false) produce larger sizes because they are taking the size of an int literal, which is at least sizeof(int).
boolis smaller than you expected, how did you not allocate enough memory?boolthat always resulted in a segmentation fault until we multiplied themalloc(x*sizeof(bool))bymalloc(4*x*sizeof(bool))It could have been something completely different, but that solved the problem and led me to this question.x*sizeof(bool)? For the first two levels, which are pointers-to-pointers, you would have to allocatesizeof(bool*)becausesizeof(bool*)is likely not equal tosizeof(bool).x*sizeof(bool)for every level. But now that you mention it, (and I sit and think about it) we would need to allocate memory for the pointer and not the actualboolfor all levels except the last. Wow! As I mentioned in your answer, this has been very educational and helpful!x*sizeof(bool*)instead ofx*sizeof(bool). This way you won't have to do something like4*x*sizeof(bool), because that would only help you on systems where pointers are 4-bytes wide (32-bit programs). In a 64-bit program, you'd run into memory crashes again.sizeof(bool*)will work correctly on either 32-bit or 64-bit.