That's is not true sadly , I can access p[i] there is value on 0
there... – Raz Ben Netanel 29 mins ago
So here is your next experiment - but this is just a learning exercise! As usual, you should not try this at home.
int t213(void)
{
// let me create an array of ints on the stack
int buff[128];
// and initialize them to a distinctive patterh
for (int i=0; i<128; i++) buff[i] = 0x55555555;
void* place0 = buff; // offset 0 into buff
// if you want, try printing buff[0] (and maybe 1 or 2 more)
// use hex to see the 55555555 pattern
// next I use placement new to do something that makes everyone
// (familiar with UB) uncomfortable ... Relax, I have an embedded
// software background and understand that the behavior we shall
// observe is not guaranteed, not even from 1 compile to the next
int* p1 = new (place0) int(7); // a single int, initialized to 7,
void* p1Addr = p1; // at location place0
// (no - I know your thinking about it, but don't do this.
// essentially because neither C nor C++ have memory layout symantics.)
dtbAssert(p1Addr == place0)(p1Addr)(place0); // no assert occurs
// both addresses are the same
// test the soup
std::cout << "\np1 : " << std::setw(12) << std::hex << *p1 << " @" << DTB::hexComma(p1Addr)
<< "\nbuff[0] : " << std::setw(12) << std::hex << buff[0] << " @" << DTB::hexComma(&buff[0])
<< "\nbuff[1] : " << std::setw(12) << std::hex << buff[1] << " @" << DTB::hexComma(&buff[1])
<< std::endl;
// now spoil the soup:
p1[1] = 0xdeadbeef; // oops - UB NO COMPILER WARNING
// then test the soup once more
std::cout << "\np1 : " << std::setw(12) << std::hex << *p1 << " @" << DTB::hexComma(p1Addr)
<< "\nbuff[0] : " << std::setw(12) << std::hex << buff[0] << " @" << DTB::hexComma(&buff[0])
<< "\nbuff[1] : " << std::setw(12) << std::hex << buff[1] << " @" << DTB::hexComma(&buff[1])
<< std::endl;
return(0);
}
And since I used some private tools, I will include the output:
p1 : 7 @7ffe,c3bb,3910
buff[0] : 7 @7ffe,c3bb,3910
buff[1] : 55555555 @7ffe,c3bb,3914
p1 : 7 @7ffe,c3bb,3910
buff[0] : 7 @7ffe,c3bb,3910
buff[1] : deadbeef @7ffe,c3bb,3914
Note the code line marked with the comment "// oops - UB ".
That line uses p1[1]. But the out-of-bound index is not noticed by the compiler - not even a warning.
Because it is UB, the compiler generated what-ever it wanted to. In this case (but not guaranteed), it is as if p1[1] exists -- note that buff[1] changes from 55555555 to deadbeef
Research term - degenerate pointer