Example given:
1 2 3 4 5 6 7 8 9 10 11 | int main(int argc, char *argv[]) { unsigned int integer = 255; unsigned int *pointerInt = &integer; printf("char %d\n", *pointerInt); unsigned char *pointerChar = (unsigned char *)pointerInt; printf("char %d\n", *pointerChar); } |
This would print
1 2 | char 255 char 255 |
If I increase integer to 256 the result is as expected:
1 2 | char 256 char 0 |
The char jumps back to 0 if its boundaries are reached.
However what happens here:
1 2 3 4 5 6 7 8 9 10 11 | int main(int argc, char *argv[]) { unsigned char integer = 255; unsigned char *pointerChar = &integer; printf("char %d\n", *pointerChar); unsigned int *pointerInt = (unsigned int *)pointerChar; printf("char %d\n", *pointerInt); } |
This will print:
1 2 | char 255 char "random unexpected number" |
Does this happen because the pointer reads more memory than I actually set?
And how actually does the stack work?
If I had something like this:
1 2 3 4 5 6 7 8 9 10 11 12 | int main(int argc, char *argv[]) { unsigned char integer = 255; unsigned int integer = 3000; unsigned char *pointerChar = &integer; printf("char %d\n", *pointerChar); unsigned int *pointerInt = (unsigned int *)pointerChar; printf("char %d\n", *pointerInt); } |
Would then the value pointerInt points to be consistent every time the program is executed?
My thinking is: Even If I would read further than the char's boundaries as I'm doing it with pointerInt, the value presented by pointerInt should be the same because I set the memory after integer to integer2.
So going through it
I write "integer" to the stack. Then I write "integer2" to the stack.
I print "integer". Its 255.
I increase the range size of pointerInt. So pointerInt points to the same location as pointerChar did before. But I's range is bigger because its of type int. So it should now read "char integer" and 3/4rth of "char integer2".
I print the value. It should be something consisting out of 255 and 3000 due to the stack being consistent right?
I tested it but it isn't. Why?