简体   繁体   English

C-使用memcpy直接从内存复制

[英]C - copying directly from memory using memcpy

This is purely a homework assignment question, since I'm aware that you really shouldn't be trying to do this in real life. 这纯粹是一个作业分配问题,因为我知道您真的不应该在现实生活中尝试这样做。 But I've been trying to get this right. 但是我一直在努力做到这一点。 Say we know the permanent start position of where we want to copy and the exact size of the chunk of memory we want to copy. 假设我们知道要复制的位置的永久起始位置以及要复制的内存块的确切大小。 So say our source is a stack from 0x28000 to 0x2C0000. 可以这么说,我们的来源是从0x28000到0x2C0000的堆栈。 The stack grows downwards, so we're given a pointer to the top of the stack (0x2C0000). 堆栈向下增长,因此我们获得了指向堆栈顶部的指针(0x2C0000)。 We want to copy STACK_SIZE bytes over to a second stack, the top of which is at 0x30000. 我们想将STACK_SIZE字节复制到第二个堆栈,其顶部是0x30000。 Basically something like this: 基本上是这样的:

                Stack 1            Stack 2
       /--+-------------------+-------------------+--/
          |        ABXLQPAOSRJ|                   |
       /--+-------------------+-------------------+--/
      0x280000           0x2C0000            0x300000
                              ^                   ^
                              |                   |
                         Top of stack 1     Top of Stack 2

If we have to use memcpy, we would have to start at 0x28000 right? 如果必须使用memcpy,则必须从0x28000开始吧? (I'm not entirely sure in which direction memcpy reads; from higher address to lower or vice versa) Would this be correct? (我不完全确定memcpy从哪个方向读取;从较高地址到较低地址,反之亦然)这是正确的吗?

void* s = (void *)source_stack_bottom      //where source_stack_bottom is 0x280000 in this case
void* d = (void *)dest_stack_bottom    //which is 0x2C0000
memcpy(d, s, STACK_SIZE)          //STACK_SIZE is just a variable with the stack size

I can't think of why it shouldn't work, but then again I'm still rather confused about how C allocates memory at times so... 我想不出为什么它不起作用,但是我还是对C有时如何分配内存感到困惑。

EDIT:: Oops, variable confusion. 编辑::糟糕,变量混乱。 Fixed now. 立即修复。

A naive implementation of memcpy() would be something like this: memcpy()实现是这样的:

void naive_memcpy(void *destt, void *sourcet, size_t size)
{
   char *source = (char *)sourcet;
   char *dest = (char *)destt;
   for(size_t s = 0; s < size; s++){ *dest++ = *source++; }
}

So yes, it counts upwards from the start of source and dest 所以是的,它从sourcedest开始算起

Yes, memcpy() counts up from the base addresses you pass to it. 是的, memcpy()从传递给它的基址开始计数。

You might very well need to do something like this if you ever end up writing 'bare-metal' sort of OS-less software for embedded systems, or possibly if you're implementing an operating system or kernel yourself. 如果最终为嵌入式系统编写了“裸机”的无操作系统软件,或者您自己实现了操作系统或内核,那么您可能非常需要做这样的事情。

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

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