logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git

sizeof.c (1541B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <limits.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #define FORMAT_M "sizeof(%s) == %d bytes; %d bits; (MIN:MAX) == (%d:%d)\n"
  10. static void
  11. print_size(size_t size, char *type)
  12. {
  13. int ret = printf("sizeof(%s) == %zd bytes; %zd bits\n", type, size, size * CHAR_BIT);
  14. if(ret < 0)
  15. {
  16. exit(1);
  17. }
  18. }
  19. int
  20. main(void)
  21. {
  22. int c, ret;
  23. ret = printf("CHAR_BIT == %d\n", CHAR_BIT);
  24. if(ret < 0)
  25. {
  26. exit(1);
  27. }
  28. c = sizeof(int);
  29. /* flawfinder: ignore. Not given by user but by a macro */
  30. ret = printf(FORMAT_M, "int", c, c * CHAR_BIT, INT_MIN, INT_MAX);
  31. if(ret < 0)
  32. {
  33. exit(1);
  34. }
  35. c = sizeof(char);
  36. /* flawfinder: ignore. Not given by user but by a macro */
  37. ret = printf(FORMAT_M, "char", c, c * CHAR_BIT, CHAR_MIN, CHAR_MAX);
  38. if(ret < 0)
  39. {
  40. exit(1);
  41. }
  42. print_size(sizeof(uint8_t), "uint8_t");
  43. print_size(sizeof(short), "short");
  44. print_size(sizeof(double), "double");
  45. print_size(sizeof(long), "long");
  46. print_size(sizeof(double long), "double long");
  47. print_size(sizeof(long long), "long long");
  48. print_size(sizeof(long int), "long int");
  49. print_size(sizeof(char[BUFSIZ]), "char[BUFSIZ]");
  50. print_size(sizeof(char[256]), "char[256]");
  51. print_size(sizeof(char[32]), "char[32]");
  52. print_size(sizeof(char[2]), "char[2]");
  53. print_size(sizeof('a'), "'a'");
  54. return 0;
  55. }