fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cstring>
  5.  
  6. #define LOG(index, cv, ncv) std::cout \
  7.   << std::dec << index << ".- Address = " \
  8.   << std::hex << &cv << "\tValue = " << cv << '\n' \
  9.   << std::dec << index << ".- Address = " \
  10.   << std::hex << &ncv << "\tValue = " << ncv << '\n'
  11.  
  12. // Try with no-const reference
  13. void change_with_no_const_ref(const unsigned int &const_value)
  14. {
  15. unsigned int &no_const_ref = const_cast<unsigned int &>(const_value);
  16. no_const_ref = 0xfabada;
  17. LOG(1, const_value, no_const_ref);
  18. }
  19.  
  20. // Try with no-const pointer
  21. void change_with_no_const_ptr(const unsigned int &const_value)
  22. {
  23. unsigned int *no_const_ptr = const_cast<unsigned int *>(&const_value);
  24. *no_const_ptr = 0xb0bada;
  25. LOG(2, const_value, (*no_const_ptr));
  26. }
  27.  
  28. // Try with c-style cast
  29. void change_with_cstyle_cast(const unsigned int &const_value)
  30. {
  31. unsigned int *no_const_ptr = (unsigned int *)&const_value;
  32. *no_const_ptr = 0xdeda1;
  33. LOG(3, const_value, (*no_const_ptr));
  34. }
  35.  
  36. // Try with memcpy
  37. void change_with_memcpy(const unsigned int &const_value)
  38. {
  39. unsigned int *no_const_ptr = const_cast<unsigned int *>(&const_value);
  40. unsigned int brute_force = 0xba51c;
  41. std::memcpy(no_const_ptr, &brute_force, sizeof(const_value));
  42. LOG(4, const_value, (*no_const_ptr));
  43. }
  44.  
  45. void change_with_union(const unsigned int &const_value)
  46. {
  47. // Try with union
  48. union bad_idea
  49. {
  50. const unsigned int *const_ptr;
  51. unsigned int *no_const_ptr;
  52. } u;
  53.  
  54. u.const_ptr = &const_value;
  55. *u.no_const_ptr = 0xbeb1da;
  56. LOG(5, const_value, (*u.no_const_ptr));
  57. }
  58.  
  59. int main(int argc, char **argv)
  60. {
  61. unsigned int value = 0xcafe01e;
  62. change_with_no_const_ref(value);
  63. change_with_no_const_ptr(value);
  64. change_with_cstyle_cast(value);
  65. change_with_memcpy(value);
  66. change_with_union(value);
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0s 2900KB
stdin
Standard input is empty
stdout
1.- Address = 0xbff0f5dc	Value = fabada
1.- Address = 0xbff0f5dc	Value = fabada
2.- Address = 0xbff0f5dc	Value = b0bada
2.- Address = 0xbff0f5dc	Value = b0bada
3.- Address = 0xbff0f5dc	Value = deda1
3.- Address = 0xbff0f5dc	Value = deda1
4.- Address = 0xbff0f5dc	Value = ba51c
4.- Address = 0xbff0f5dc	Value = ba51c
5.- Address = 0xbff0f5dc	Value = beb1da
5.- Address = 0xbff0f5dc	Value = beb1da