Page 1 of 1

memory...bytes.....c....but?

Posted: Mon Aug 22, 2005 8:47 am
by datajack
how would i say...copy 4096 bytes of data from pointer dest, to pointer src? and explaination would be really nice :)

Re:memory...bytes.....c....but?

Posted: Mon Aug 22, 2005 9:11 am
by AR
That is an extremely basic operation, just set the contents of destination pointer to the contents of the source pointer, incrementing both as you go, ie.

Code: Select all

for(size_t i = 0 ; i < NUMBYTES ; ++i)
     destination[i] = source[i];
Or the more optimized version:

Code: Select all

__asm__ ("rep\n\t"
         "movsb\n\t" : : "eDi"(destination), "eSi"(source), "ecx"(NumBytes));

Re:memory...bytes.....c....but?

Posted: Mon Aug 22, 2005 9:57 am
by datajack
shouldent it be *dest = *src?

and, is size_t important or can it be int i?

Re:memory...bytes.....c....but?

Posted: Mon Aug 22, 2005 10:30 am
by durand
size_t is defined as an unsigned int.

Code: Select all

typdef unsigned int size_t;

void* memcpy( char *dest, const char *src, size_t n )
{ 
  size_t i;

  for ( i = 0; i < n; i++ )
    dest[i] = src[i];

  return dest;
}

It won't be *dest because the is already indexing into the array at dest.

Try and find some tutorials on pointers. It will save you a lot of headaches.

Code: Select all

int a = 5;         // a is now == 5
int *b = &a;     // b is now pointing to a
int **d = &b;   // d is now a pointer to a pointer. *d == b and **d == a.


printf("%i %i %i", a, *b, **d );  // prints three 5's.

a = 2;  // everything points to a, so this will change the output for everything.

printf("%i %i %i", a, *b, **d );  // prints three 2's.

printf("%p", b );  // prints b which is a pointer to a. 

// So, it's printing the memory location of a.

printf("%p", d );  // prints d which is a pointer to b. 

// So, it's printing the memory location of b.

printf("%p", *d );  // prints *d which is the value of b which is a pointer to a. 

// So, it's printing the memory location of a.


Re:memory...bytes.....c....but?

Posted: Mon Aug 29, 2005 6:38 pm
by Joel (not logged in)
shouldent it be *dest = *src?

and, is size_t important or can it be int i?


size_t is whatever the appropriate data type for storing a size on the current platform is. In general, it's probably better to use size_t and not go around it by using what it's typedef'd as.

As for the memory copying, unless you're implementing the C standard library or doing a programming assignment, the standard library function memcpy already does this for you, and (unless you have a useless compiler vendor) it's probably faster than anything you would implement by hand.

Re:memory...bytes.....c....but?

Posted: Mon Aug 29, 2005 8:51 pm
by AR
He created this after being told that the question was more C-like then OS Dev-like, so... he's implementing the C library.