I am having trouble trying to implement a custom strcpy function which is supposed to handle cases where the src string is larger than the destination string. Here I have provided some code so that you guys can see the entire function. My issue is that every time I increment *dest, it goes into a null address despite the fact that I have allocated enough memory to fit all of src in it. This causes the a segmentation fault in (double pointer)dest = *src. dest is stored as a char** because in reality, the argument that has to be passed is another string that is possibly of a smaller size than src, and I wish to overwrite *dest as safely as I can.
int customStrCpy(char** dest, char* src){
int strlen1 = strlen(*dest), strlen2 = strlen(src);
if(strlen1 < strlen2){
//Creates a dynamically allocated array that is big enough to store the contents of line2.
*dest = calloc(strlen2, sizeof(char));
char* backup_str = *dest;
int copy_arrs;
for(copy_arrs = 0; copy_arrs < strlen2; copy_arrs++){
**dest = *src;
*dest++; src++;
}
*dest = backup_str;
}
else strcpy(*dest, src);
}
In the end, (char**)dest is supposed to be pointing to the correct string.