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

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.


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 in JMP[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);
链接地址: http://www.djcxy.com/p/28378.html

上一篇: 代码片段警告:从不同大小的整数转换为指针

下一篇: 从不同大小的整数转换为指针