简体   繁体   中英

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. The stack grows downwards, so we're given a pointer to the top of the stack (0x2C0000). We want to copy STACK_SIZE bytes over to a second stack, the top of which is at 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? (I'm not entirely sure in which direction memcpy reads; from higher address to lower or vice versa) Would this be correct?

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...

EDIT:: Oops, variable confusion. Fixed now.

A naive implementation of memcpy() would be something like this:

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

Yes, memcpy() counts up from the base addresses you pass to it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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