0

I have this code snippet and I have no idea why it's working in my code.

mft_fragment *pfrag = malloc(sizeof(mft_fragment));
printf("size2:%lu\n", sizeof(mft_fragment));
pfrag[23].fragment_count = 10;

printf prints 8 bytes. Shouldn't I be getting segmentation fault or something like that?

  • No. If code breaks the rules, anything may happen. C does not require a net. If code [falls off the tightrope](http://i.dailymail.co.uk/i/pix/2012/06/14/article-2159007-059F0F4D000005DC-442_634x494.jpg), you may get hurt – chux - Reinstate Monica Jan 06 '18 at 02:45
  • *Shouldn't I be getting segmentation fault or something like that?* Not necessarily, that's undefined behaviour, anything goes, it might crash with segfault, you might even start world war 3 :) – Pablo Jan 06 '18 at 02:47
  • C has no built-in bounds checking. That is up to you as a developer to take care of. This is simply *undefined behaviour*. – Sani Huttunen Jan 06 '18 at 02:48
  • Also `"%ld"` is not necessarily the matching f specifier for the result of `sizeof(mft_fragment)`. Use `"%zu"` – chux - Reinstate Monica Jan 06 '18 at 02:49
  • @SaniSinghHuttunen An implementation _may_ have built-in bounds checking. It is all UB. – chux - Reinstate Monica Jan 06 '18 at 02:50
  • ah, thanks guys, found the mistake –  Jan 06 '18 at 02:51
  • @chux: Yes, but the C standard (C99 or whatever) has no built-in bounds checking. As the question is tagged only as `C` and not to a specific implementation the standards are all we can compare with. – Sani Huttunen Jan 06 '18 at 02:51
  • @SaniSinghHuttunen I think you misunderstood the standard, UB mean implementation is free to do whatever it wants, that include do bound checking and delete all files of your system and more ;) – Stargateur Jan 06 '18 at 03:11

0 Answers0