Function pointer assignment and memset'ing - What's happening here?

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.
 
S

Shao Miller

'(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

Or, more accurately for the second one:

puts == *puts --> &puts == *&puts --> &puts == puts --> &puts == &puts
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top