S
Shao Miller
First thank you for the explanation. I'm on x86-32, and doing
something that's very specific and so I'm almost sure there's no way
to stay 'portable'. I'm loading an a.out file on memory, subjected to
some constraints, and I do need to write the 4 byte-address of (say)
puts function in a certain memory location. My code does work as
expected using the following line:
*((int *)(data+curr_reloc->r_address)) = puts;
, but when I tried to replace it with a less ugly one and wasn't
successful and I was kind of confused on how "*puts", "&puts" and
"puts" produced the same result when trying to replace this line and
specially on how I couldn't find an equivalent line using memcpy.
I'd suggest using a function pointer:
/* Function type definition, compatible with 'puts' */
typedef int f_puts(const char *);
/* Function pointer to point to 'puts' */
f_puts * puts_ptr = puts;
/* Copy the stored pointer value to the desired slot */
memcpy(data + curr_reloc->r_address, &puts_ptr, sizeof puts_ptr);
/* Or: Assign a pointer to 'puts' to the slot, directly */
*(f_puts **) (data + curr_reloc->r_address) = puts;
'(puts == &puts && puts == *puts)' is always true (given #include
<stdio.h>). This is because some conversions happen:
puts == &puts --> &puts == &puts
puts == *puts --> &puts == puts --> &puts == &puts
You can check that 'sizeof &puts == 4' before either the 'memcpy' or the
assignment.