'Why function pointer in the structure causes relocation at program load-time
I've the following code that I compile and run on Linux:
#include <stdio.h>
// can't be static
void do_stuff(void) {
;;
}
typedef void (*func)(void);
struct data {
func ptr;
};
static const struct data d = {
.ptr = do_stuff
};
int main() {
d.ptr();
}
If I compile it:
gcc -O0 -o main main.c
then d
goes to .data.rel.ro segment.
objdump -t main | grep ".data.rel.ro"
0000000000003df8 l d .data.rel.ro 0000000000000000 .data.rel.ro
0000000000003df8 l O .data.rel.ro 0000000000000008 d
I understand that reason for it is a relocation done by loader and that's because of function pointer in the "data" structure.
What I don't get is - why it is done like that? What is a reason for having relocation here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|