I'm really confused by how uint32_t
pointers work in C++
I was just fiddling around trying to learn TEA, and I didn't understand when they passed a uint32_t parameter to the encrypt function, and then in the function declared a uint32_t variable and assigning the parameter to it as if the parameter is an array.
Like this:
void encrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i;
So I decided to play around with uint32_t pointers, and wrote this short code:
int main ()
{
uint32_t *plain_text;
uint32_t key;
unsigned int temp = 123232;
plain_text = &temp;
key = 7744;
cout << plain_text[1] << endl;
return 0;
}
And it blew my mind when the output was the value of "key". I have no idea how it works... and then when I tried with plain_text[0], it came back with the value of "temp".
So I'm stuck as hell trying to understand what's happening.
Looking back at the TEA code, is the uint32_t* v
pointing to an array rather than a single unsigned int? And was what I did just a fluke?
uint32_t
is a type. It means unsigned 32-bit integer. On your system it is probably a typedef name for unsigned int
.
There's nothing special about a pointer to this particular type; you can have pointers to any type.
The []
in C and C++ are actually pointer indexing notation. p[0]
means to retrieve the value at the location the pointer points to. p[1]
gets the value at the next memory location after that. Then p[2]
is the next location after that, and so on.
You can use this notation with arrays too because the name of an array is converted to a pointer to its first element when used like this.
So, your code plain_text[1]
tries to read the next element after temp
. Since temp
is not actually an array, this causes undefined behaviour. In your particular case, the manifestation of this undefined behaviour is that it managed to read the memory address after temp
without crashing, and that address was the same address where key
is stored.