Is memcpy of a pointer the same as assignment?

前端 未结 9 1061
你的背包
你的背包 2020-12-03 16:23

Introduction: This question is part of my collection of C and C++ (and C/C++ common subset) questions regarding the cases where pointers object with strictly ide

9条回答
  •  忘掉有多难
    2020-12-03 17:06

    Undefined behaviour: A play in n parts.

    Compiler1 and Compiler2 enter, stage right.

    int a[1] = { 0 }, *pa1 = &a[0] + 1, b = 1, *pb = &b;
    

    [Compiler1] Hello, a, pa1, b, pb. How very nice to make your acquaintance. Now you just sit right there, we're going to look through the rest of the code to see if we can allocate you some nice stack space.

    Compiler1 looks through the rest of the code, frowning occasionally and making some markings on the paper. Compiler2 picks his nose and stares out the window.

    [Compiler1] Well, I'm afraid, b, that I have decided to optimize you out. I simply couldn't detect somewhere which modified your memory. Maybe your programmer did some tricks with Undefined Behaviour to work around this, but I'm allowed to assume that there is no such UB present. I'm sorry.

    Exit b, pursued by a bear.

    [Compiler2] Wait! Hold on a second there, b. I couldn't be bothered optimizing this code, so I've decided to give you a nice cosy space over there on the stack.

    b jumps in glee, but is murdered by nasal demons as soon as he is modified through undefined behaviour.

    [Narrator] Thus ends the sad, sad tale of variable b. The moral of this story is that one can never rely on undefined behaviour.

提交回复
热议问题