How to use memcpy example

The memcpy function is declared in stdlib.h. It accepts three arguments: the destination buffer, the source buffer and the number of bytes to copy from the source memory position to destination position.

Here is the example code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void hexdump(void *ptr, int buflen) {
  unsigned char *buf = (unsigned char*)ptr;
  int i, j;
  for (i=0; i<buflen; i+=16) {
    printf("%06x: ", i);
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%02x ", buf[i+j]);
        printf("   ");
    printf(" ");
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');
int main (int argc, char ** argv) {
    int buf[1024];
    buf[1] = 0xffffffff;
    char * s = "bazzar";
    //memcpy(buf, s, strlen(s));
    memcpy(buf, s, strlen(s) + 1);
    printf("buf is %s", buf);
    hexdump(buf, 1024);

In the code, we copy a string to a memory buffer, and print the memory in the buffer as hexadecimal, notice the memcpy will copy exactly number of bytes as specified in the third argument, if you want to copy the string with null bytes at the end you should set the length as the length of the string plus one.