Why does this intentionally incorrect use of strcpy not fail horribly?

后端 未结 5 534
鱼传尺愫
鱼传尺愫 2020-11-29 09:28

Why does the below C code using strcpy work just fine for me? I tried to make it fail in two ways:

1) I tried strcpy from a string literal

5条回答
  •  长情又很酷
    2020-11-29 10:29

    Overwriting beyond the bounds of allocated memory causes Undefined Behavior.
    So in a way yes you got lucky.

    Undefined behavior means anything can happen and the behavior cannot be explained as the Standard, which defines the rules of the language, does not define any behavior.

    EDIT:
    On Second thoughts, I would say you are really Unlucky here that the program works fine and does not crash. It works now does not mean it will work always, In fact it is a bomb ticking to blow off.

    As per Murphy's Law:
    "Anything that can go wrong will go wrong"["and most likely at the most inconvenient possible moment"]

    [ ]- Is my edit to the Law :)

提交回复
热议问题