Is memcpy of a pointer the same as assignment?

前端 未结 9 1060
你的背包
你的背包 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:00

    The question, as I understand it, is:

    Is memcpy of a pointer the same as assignment?

    And my answer would be, yes.

    memcpy is basically an optimized assignment for variable length data that has no memory alignment requirements. It's pretty much the same as:

    void slow_memcpy(void * target, void * src, int len) {
      char * t = target;
      char * s = src;
      for (int i = 0; i < len; ++i)
      {
        t[i] = s[i];
      }
    }
    

    is a pointer's semantic "value" (its behavior according to the specification) determined only by its numerical value (the numerical address it contains), for a pointer of a given type?

    Yes. There are no hidden data fields is C, so the pointer's behavior is totally dependant on it's numerical data content.

    However, pointer arithmetics is resolved by the compiler and depends on the pointer's type.

    A char * str pointer arithmetics will be using char units (i.e., str[1] is one char away from str[0]), while an int * p_num pointer arithmetics will be using int units (i.e., p_num[1] is one int away from p_num[0]).

    Are two pointers with identical bit patterns allowed to have different behavior? (edit)

    Yes and no.

    They point to the same location in the memory and in this sense they are identical.

    However, pointer resolution might depend on the pointer's type.

    For example, by dereferencing a uint8_t *, only 8 bits are read from the memory (usually). However, when dereferencing a uint64_t *, 64 bits are read from the memory address.

    Another difference is pointer arithmetics, as described above.

    However, when using functions such as memcpy or memcmp, than the pointers will behave the same.


    So why does everybody say "No"?

    Well, that's because the code in your example doesn't reflect the question in the title. The code’s behavior is undefined, as clearly explained by the many answers.

    (edit):

    The issues with the code have little to do with the actual question.

    Consider, for example, the following line:

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

    In this case, pa points to a[1], which is out of bounds.

    This pretty much throws the code into undefined behavior territory, which distracted many answers away from the actual question.

提交回复
热议问题