memcpy with destination pointer to const data

前端 未结 3 582
我在风中等你
我在风中等你 2021-01-13 04:41

I always thought that an statement like const int *a means a is an int pointer to const data and as such one should not b

相关标签:
3条回答
  • 2021-01-13 05:15

    Casts usually suppress warnings. There is a gcc option, -Wcast-qual that will warn you about casts that are losing a const or volatile qualifier.

    The program ran successfully because the memory used to store the array wasn't actually readonly, because they were allocated on the stack. This is an implementation detail and technically your code could have crashed if the implementation was really strict.

    Declare a and b as globals and there's a greater chance it will crash (still not a guarantee)

    0 讨论(0)
  • 2021-01-13 05:26

    Casting to void* removes the association with an int - by throwing away the type, you throw away the type decorators, such as const

    Edit

    As from discussion below, I want to make clear, that the important part is not to what you cast (void* in the OQ), but the fact that you cast - this implies throwing away your original type and its decorators.

    0 讨论(0)
  • 2021-01-13 05:36

    You told the compiler to disregard the initial declaration when you performed the cast. It listened. That doesn't mean that your program is correct however. Modifying what was originally declared to be const results in undefined behavior (for example, the compiler is free to store that data in read only memory).

    C doesn't hold your hand. If you chose to do something dangerous then it will let you.

    0 讨论(0)
提交回复
热议问题