Jona
Jona

Reputation: 1825

memcpy - cast to pointer from integer of different size

I am trying to use memcpy but it gives me a

runtime error : Segmentation fault (Core dumped)

and a compiler warning: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

this is the code

unsigned char JMP[6] = {0xE9, 0x90, 0x90, 0x90, 0x90, 0xC3};
unsigned long JMPSize = ...;

//copy jump size to jump instruction at second byte (this is where i get the error)
memcpy((uint8_t*)JMP[1],(void*)JMPSize, 4);

Upvotes: 2

Views: 4835

Answers (2)

jbr
jbr

Reputation: 6258

Neither JMP or JMPSize pointers but values. So when you cast the variables to pointers, then memcpy will try to copy from the address number stored inJMP[0], to the address number stored in JMPSize. Theses memory locations are probably not valid, which makes your program segfault.

Instead you should reference your variables, that is what the & operator in C is for:

memcpy(&JMP[1], &JMPSize, 4);

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

Neither JMP[1] nor JMPSize are pointers. This means that memcpy will interpret the actual values of the variables as pointers, which will then point to somewhere way off and lead to undefined behavior.

You need to use the address-of operator & to make them pointers:

memcpy(&JMP[1], &JMPSize, 4);

Generally, if a functions takes a void * argument, or returns void *, then don't cast the types. Not casting the types will give you warnings, and warnings are in many cases indicators of undefined behavior.

Upvotes: 6

Related Questions