-1

Refer to this answer https://stackoverflow.com/a/1422774/16238824

Whatever the garbage value is, I guess we can overwrite it (in order to assign a value).

So how does garbage value cause segmentation fault?

WYZku
  • 3
  • 3

1 Answers1

0

A segmentation fault is triggered by the operating system when you access protected memory that does not belong to your application. Not every operating system offers protected memory, and in fact the "garbage values" and "segmentation fault" are actually byproducts of the same underlying issue; you are triggering undefined behavior. On some implementations, the memory will be initialized to sane default values. On some implementations, the memory will be in whatever state the last process to write to that memory held.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Generic "sane default values" are a myth. All bits zero (generally nowadays synonymous to null pointer, zero, false, or positive zero, depending on type) is not always a sane choice. – Deduplicator Jun 27 '21 at 01:52
  • @Deduplicator As long as it is documented and predictable it is "sane". We can at least discuss it. But of course, the code still won't be truly portable because *anything* could happen when you invoke undefined behavior. – Elliott Frisch Jun 27 '21 at 01:58