Does integer overflow cause undefined behavior because of memory corruption?

前端 未结 6 740
Happy的楠姐
Happy的楠姐 2020-12-25 10:53

I recently read that signed integer overflow in C and C++ causes undefined behavior:

If during the evaluation of an expression, the result is not math

6条回答
  •  攒了一身酷
    2020-12-25 11:34

    Undefined behaviour is undefined. It may crash your program. It may do nothing at all. It may do exactly what you expected. It may summon nasal demons. It may delete all your files. The compiler is free to emit whatever code it pleases (or none at all) when it encounters undefined behaviour.

    Any instance of undefined behaviour causes the entire program to be undefined - not just the operation that is undefined, so the compiler may do whatever it wants to any part of your program. Including time travel: Undefined behavior can result in time travel (among other things, but time travel is the funkiest).

    There are many answers and blog posts about undefined behaviour, but the following are my favorites. I suggest reading them if you want to learn more about the topic.

    • A Guide to Undefined Behavior in C and C++, Part 1
    • What Every C Programmer Should Know About Undefined Behavior #1/3

提交回复
热议问题