简体   繁体   English

memcpy-从不同大小的整数转换为指针

[英]memcpy - cast to pointer from integer of different size

I am trying to use memcpy but it gives me a 我正在尝试使用memcpy,但它给了我一个

runtime error : Segmentation fault (Core dumped) 运行时错误:分段错误(核心已转储)

and a compiler warning: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 和编译器警告:警告:从不同大小的整数强制转换为指针[-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. JMP[1]JMPSize是指针。 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. 这意味着memcpy将把变量的实际值解释为指针,这将指向某个遥远的地方并导致未定义的行为。

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. 通常,如果函数采用void *参数或返回void * ,则不要强制转换类型。 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. JMPJMPSize指针都不是值。 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 . 因此,当您将变量转换为指针时,memcpy将尝试从存储在JMP[0]中的地址号复制到存储在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: 相反,您应该引用变量,这就是C中的&运算符的作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM