简体   繁体   English

数组中的C ++内存混乱

[英]c++ memory mess in arrays

Why does this happen? 为什么会这样?

u_char macDst[6], macSrc[6], ipType[2]={0x88, 0x92};
u_char header[] = {0x04,0x00,0x20,0x00,...,};
const int len = sizeof(macDst) + sizeof(macSrc) + sizeof(header) + 2;
u_char* pck[len];

int j = 0, length = sizeof(macDst);
for (j; j < length; j++)
{
    pck[j] = &macDst[j];
}
length += sizeof(macSrc);

for (j; j < length; j++)
{
    pck[j] = &macSrc[j - sizeof(macDst)];
}

pck[j++] = &ipType[0];
pck[j++] = &ipType[1];

length += sizeof(header) + 2;

for (j; j < len; j++)
{
    pck[j] = &header[j - sizeof(macDst) - sizeof(macSrc)];
}
u_char testSend[170];

memcpy(testSend, *pck, sizeof(pck));

The var testSend only has macDst values (before initialized), while in the pointer I have all of them. var testSend仅具有macDst值(在初始化之前),而在指针中,我具有所有这些值。 If I copy them one by one, I get a good result: 如果将它们一张一张地复制,我会得到很好的结果:

for (int k = 0; k < 170; k++)
{
    testSend[k] = *pck[k];
}

Any idea?? 任何想法??

Thanks!! 谢谢!!

Edit: 编辑:

This is a physic problem: 这是一个物理问题:

-----ooooooooo------------aaaa----bbbb----
- Null Data

When I make the pointers array I am doing this: 当我创建指针数组时,我正在这样做:

oooooooooaaaabbbb

But when I sent the packet and when I did the memcpy (or memmove) I was saying this: take this pointer and this amount of memory and copy them: 但是,当我发送数据包以及执行memcpy(或memmove)时,我是这样说的:使用此指针和此数量的内存并复制它们:

----|oooooooooo----------|----aaaaa----bbbb----

being the amount the sum of the 3 memory places. 是3个存储位置的总和。

I find the code convoluted, and I would never write it this way. 我发现代码很复杂,我永远不会这样写。 Still, the error here: 仍然,这里的错误:

memcpy(testSend, *pck, sizeof(pck));

You are dereferencing pck - and point to the first element, which is a char* . 您正在取消引用pck并指向第一个元素,即char* This is what you copy using your memcpy. 这是使用memcpy复制的内容。 On the other hand, your hand-written loop does dereference the pointer before copying it. 另一方面,您的手写循环确实在复制指针之前取消了对指针的引用。

Fill the testSend array directly: 直接填充testSend数组:

u_char *p = testSend;
memcpy(p, macDst, sizeof(macDst)); p += sizeof(macDst);
memcpy(p, macSrc, sizeof(macSrc)); p += sizeof(macSrc);
memcpy(p, ipType, sizeof(ipType);  p += sizeof(ipType);
memcpy(p, header, sizeof(header));

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

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