Reverse Engineering for Beginners

(avery) #1
CHAPTER 23. POINTERS TO FUNCTIONS CHAPTER 23. POINTERS TO FUNCTIONS

Chapter 23


Pointers to functions


A pointer to a function, as any other pointer, is just the address of the function’s start in its code segment.

They are often used for calling callback functions^1.

Well-known examples are:


  • qsort()^2 ,atexit()^3 from the standard C library;

  • *NIX OS signals^4 ;

  • thread starting:CreateThread()(win32),pthread_create()(POSIX);

  • lots of win32 functions, likeEnumChildWindows()^5.

  • lots of places in the Linux kernel, for example the filesystem driver functions are called via callbacks:http://go.
    yurichev.com/17076

  • The GCC plugin functions are also called via callbacks:http://go.yurichev.com/17077

  • Another example of function pointers is a table in the “dwm” Linux window manager that defines shortcuts. Each
    shortcut has a corresponding function to call if a specific key is pressed:GitHub. As we can see, such table is easier
    to handle than a large switch() statement.


So, theqsort()function is an implementation of quicksort in the C/C++ standard library. The functions is able to sort
anything, any type of data, as long as you have a function to compare these two elements andqsort()is able to call it.
The comparison function can be defined as:

int (*compare)(const void *, const void *)

Let’s use a slightly modified example which was foundhere:

1 / ex3 Sorting ints with qsort /
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 int comp(const void _a, const void _b)
7 {
8 const int a=(const int )_a;
9 const int b=(const int )_b;
10
11 if (a==b)
12 return 0;
13 else
14 if (a < b)
15 return -1;
16 else
17 return 1;
18 }
19
20 int main(int argc, char* argv[])


(^1) wikipedia
(^2) wikipedia
(^3) http://go.yurichev.com/17073
(^4) wikipedia
(^5) MSDN

Free download pdf