Home > Mobile >  In this program I have written my own memcopy function. I am printing destination string in the main
In this program I have written my own memcopy function. I am printing destination string in the main

Time:06-12

Below is the program

#include <stdio.h>
#include <stdlib.h>

void mymemcpy(void *f_dst, void *f_src, int n) {
    int j = 0;
    char *src = (char *)f_src;
    char *dst = (char *)f_dst;
    for (j = 0; j < n; j  ) {
        dst[j] = src[j];
    }
    dst[j] = "\0";
}

int main() {
    int i = 0;
    char src[100] = "HELLO WORD";
    char dst[100];

    mymemcpy(dst, src, 10);
    for (i = 0; i < 10; i  ) {
       printf("%c\t", dst[i]);
    }
    printf("\n%s", dst);
   
    return 0;
}

I am getting the output as below

H       E       L       L       O               W       O       R       D
HELLO WORD$u

why I am getting the extra two characters in the second line of output even though in the function I terminated the string with null character ?

CodePudding user response:

There are multiple problems:

  • dst[j] = "\0"; does not set a null terminator: you attempt to store a string pointer into a char. You should instead use a character constant as in dst[j] = '\0';

  • memcpy does not write anything beyond the end of the destination array. mymemcopy probably should not either. You should instead set the null terminator in main or pass a maximum count of character to printf.

Here is a modified version:

#include <stdio.h>

void mymemcpy(void *f_dst, const void *f_src, size_t n) {
    size_t j = 0;
    unsigned char *src = (unsigned char *)f_src;
    unsigned char *dst = (unsigned char *)f_dst;
    for (j = 0; j < n; j  ) {
        dst[j] = src[j];
    }
}

int main() {
    int i = 0;
    char src[100] = "HELLO WORD";
    char dst[100];

    mymemcpy(dst, src, 10);

    for (i = 0; i < 10; i  ) {
       printf("%c\t", dst[i]);
    }
    printf("\n%.10s\n", dst);
   
    return 0;
}
  • Related