2

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);
2
  • 1
    Possibly you want &JMP[1] Commented Oct 1, 2013 at 15:02
  • 1
    (uint8_t*)&JMP[1] looks like what you trying to do Commented Oct 1, 2013 at 15:02

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Jona It only fools the compiler to tread the value of what you're casting as a pointer. In the case of (uint8_t*)JMP[1], it will pass the value 0x90 to memcpy as a pointer. I doubt the value 0x90 is pointing to a valid writable area.
@Jona: A cast only converts the value you give it. It does not take the address of the object you give it. So (void *) JMPSize takes the value of JMPSIZE and changes its type to a pointer. That gives you a pointer whose value is nonsense, not a proper address. To get the address of an object, you use the & operator.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.