C++ 将整数复制到缓冲区memcpy C++;

C++ 将整数复制到缓冲区memcpy C++;,c++,pointers,C++,Pointers,基本上,我希望将指针的地址存储在缓冲区中。别问我为什么 char * buff = "myBuff"; char * myData = (char*)malloc(sizeof(char*)); int addressOfArgTwo = (unsigned int)buff; memcpy(myData, &addressOfArgTwo, sizeof(char*)); cout << "Int Val: " << addressOfArgTwo <&

基本上,我希望将指针的地址存储在缓冲区中。别问我为什么

char * buff = "myBuff";
char * myData = (char*)malloc(sizeof(char*));
int addressOfArgTwo = (unsigned int)buff;
memcpy(myData, &addressOfArgTwo, sizeof(char*));

cout << "Int Val: " << addressOfArgTwo << endl;
cout << "Address in buffer:" << (unsigned int)*myData << endl;

当缓冲区中的Int Val和Address应该相同时。感谢您取消对char*的引用,生成一个char,然后将该1字节的char转换为int,而不是地址的全部4字节(如果这是32位机器,则为64位上的8字节)。4472832是444000的十六进制数。在一台小小的endian机器上,你抓取最后的00

*((unsigned int*)myData)
应显示正确的数字。

而不是:

(int)*myData 
应该是:

*((int*)myData)

正如迈克尔所说,这条线应该是

cout << "Address in buffer:" << *((unsigned int*)myData) << endl

cout这通常是危险的:

 *((unsigned int*)myData)
Intel IA-32(每个人都习惯于)支持未对齐的访问,但其他一些体系结构不支持。它们要求变量对齐(1字节边界上的8位数据、2字节边界上的16位数据和4字节边界上的32位数据)。在需要对齐的体系结构上,未对齐的访问将返回损坏的数据或引发CPU异常。在过去的工作中,我看到它在现实生活中导致了一个bug,一个微妙的bug导致了文件系统损坏,因为我们使用的软件包(在嵌入式平台上)附带了磁盘驱动程序

在这个孤立的例子中,您可以看到myData的地址来自malloc(),这意味着它适合于所有类型的指针,但是如果您不知道指针来自何处,则将较小的指针转换为较大的指针通常是一种危险的做法

从任意内存位置提取32位整数的安全方法是声明临时32位整数并对其执行复制,将源内存视为原始字符数组:

unsigned int GetUnalignedLittleEndianUInt32(void *address)
{
    unsigned char *uc_address = (unsigned char *)address;
    return (
        (uc_address[3] << 24) |
        (uc_address[2] << 16) |
        (uc_address[1] << 8) |
        uc_address[0]
    );
}
这实际上是memcpy()的反面,您首先在那里获取指针

但是,将指针视为int:

int addressOfArgTwo = (unsigned int)buff;
正如Michael指出的那样,如果在32位和64位体系结构之间移动,这也是危险的。指针并不总是32位整数。考虑使用稍后可以更改的Type。Linux上的约定是指针的大小与长指针的大小相同。在Windows上,有typedefs INT_PTR、UINT_PTR、LONG_PTR和ULONG_PTR

因此,我最后建议(在Windows上):


谢谢大家的帮助
unsigned int GetUnalignedUInt32(void *address)
{
    unsigned int value;
    memcpy(&value, address, sizeof(value));
    return value;
}
int addressOfArgTwo = (unsigned int)buff;
ULONG_PTR GetAddressAtAddress(void *address)
{
    ULONG_PTR value;
    memcpy(&value, address, sizeof(value));
    return value;
}