Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Programming 51

7 - Hello, world!
8 - Hello, world!
9 - Hello, world!
10 - Hello, world!
11 - Hello, world!
reader@hacking:~/booksrc $


Format strings are used quite often, so familiarity with them is valuable.


In addition, the ability to output the values of variables allows for debugging in


the program, without the use of a debugger. Having some form of immediate


feedback is fairly vital to the hacker’s learning process, and something as


simple as printing the value of a variable can allow for lots of exploitation.


0x265 Typecasting


Typecasting is simply a way to temporarily change a variable’s data type, despite


how it was originally defined. When a variable is typecast into a different


type, the compiler is basically told to treat that variable as if it were the


new data type, but only for that operation. The syntax for typecasting is


as follows:


(typecast_data_type) variable


This can be used when dealing with integers and floating-point variables,


as typecasting.c demonstrates.


typecasting.c


#include <stdio.h>


int main() {
int a, b;
float c, d;


a = 13;
b = 5;


c = a / b; // Divide using integers.
d = (float) a / (float) b; // Divide integers typecast as floats.


printf("[integers]\t a = %d\t b = %d\n", a, b);
printf("[floats]\t c = %f\t d = %f\n", c, d);
}


The results of compiling and executing typecasting.c are as follows.


reader@hacking:~/booksrc $ gcc typecasting.c
reader@hacking:~/booksrc $ ./a.out
[integers] a = 13 b = 5
[floats] c = 2.000000 d = 2.600000
reader@hacking:~/booksrc $

Free download pdf