How undefined is undefined behavior?

2019-01-03 16:28发布

I'm not sure I quite understand the extent to which undefined behavior can jeopardize a program.

Let's say I have this code:

#include <stdio.h>

int main()
{
    int v = 0;
    scanf("%d", &v);
    if (v != 0)
    {
        int *p;
        *p = v;  // Oops
    }
    return v;
}

Is the behavior of this program undefined for only those cases in which v is nonzero, or is it undefined even if v is zero?

8条回答
相关推荐>>
2楼-- · 2019-01-03 17:21

Your program is pretty-well defined. If v == 0 then it returns zero. If v != 0 then it splatters over some random point in memory.

p is a pointer, its initial value could be anything, since you don't initialise it. The actual value depends on the operating system (some zero memory before giving it to your process, some don't), your compiler, your hardware and what was in memory before you ran your program.

The pointer assignment is just writing into a random memory location. It might succeed, it might corrupt other data or it might segfault - it depends on all of the above factors.

As far as C goes, it's pretty well defined that unintialised variables do not have a known value, and your program (though it might compile) will not be correct.

查看更多
Animai°情兽
3楼-- · 2019-01-03 17:27

I would say it makes the whole program undefined.

The key to undefined behavior is that it is undefined. The compiler can do whatever it wants to when it sees that statement. Now, every compiler will handle it as expected, but they still have every right to do whatever they want to - including changing parts unrelated to it.

For example, a compiler may choose to add a message "this program may be dangerous" to the program if it detects undefined behavior. This would change the output whether or not v is 0.

查看更多
登录 后发表回答