Reputation: 646
Here's this code from the Art of Exploitation book by Jon Erikson. I understand the typecast on the second line makes the compiler leave you alone about data types. What I'm not sure about is why double typecasting is necessary on the bottom line.
int *int_pointer;
int_pointer = (int *) char_array;
for(i=0; i < 5; i++)
printf("[integer pointer] points to %p, which contains the char '%c'\n", int_pointer, *int_pointer);
int_pointer = (int *) ((char *) int_pointer + 1);
I am going to assume it's because leaving it like so without the (int *)
would make it increment by the correct data type character, but is this not what you want? Why typecast back to int?
And what's up with the *
inside the parenthesis? Is this de-referencing the data in the variable? Some explanation would be kindly appreciated.
Upvotes: 0
Views: 1420
Reputation: 881263
It's not typecasting to int
or char
, it's typecasting the pointer to a char
pointer or int
pointer.
When you add one to a pointer, it advances to the next item being pointed at, by scaling the increment based on the type of the item.
If the items are int
, it advances by the size of an int
. This is probably 4 or 8 in the current environment but will hopefully will be larger in future so we can stop messing about with bignum libraries :-)
If the items are of type char
, it advances by one (sizeof(char)
is always one, since ISO C defines a byte as the size of a char
rather than eight bits).
So, if you have four-byte int
types, there's a big difference between advancing an int
pointer and a char
pointer. For example, consider the following code:
int *p = 0; // bad idea but shows the concept.
p = p + 1; // p is now 4.
p = (int*)(((char*)p) + 1) // p is now 5.
That last statement breaks down as:
(char*)p - get a char pointer version of p (a)
a + 1 - add one to it (b)
(int*)b - cast it back to an int pointer (c)
p = c - replace p with that value
Upvotes: 4