0

I am writing my own memcpy() function . I am copying source string to destination . While copying , an error occurs as 'segmentation fault' . I am using codeblocks. Can anyone explain why? Am I copying strings incorrectly?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
  char info;
  struct node *next;
}mynode;


void mymemcpy(void*,const void*,size_t);

int main()
{
   char *p="sonampulkit";
   char *q=p+2;
   mymemcpy(q,p,strlen(p)+1);
   printf("\n final dest=%s ",q);
   printf("\n final src=%s ",p);
   return 0;
}

void mymemcpy(void* to,const void* from,size_t n)
{
    char *src=(char*)from;
    char *dest=(char*)to;
    printf("source=%s",src);
    printf("\ndestination=%s",dest);
    printf("\nsize=%d",n);
    int i=0;
    for(i=0;i<n;i++)
    {
       printf("\ndest=%c",*(dest+i));
       printf("\nsrc=%c",*(src+i));
       // At below line , error occurred.
       dest[i]=src[i];
    }
    return dest;
}

Error: Program received segmentation fault.

  • 1
    Modifying string literals is undefined behaviour. And it's `void *mymemcpy(void*, const void*, size_t);` not `void mymemcpy(void*, const void*, size_t);` – Jabberwocky May 15 '17 at 15:23
  • Hint: try with `char p[100] = "sonampulkit";` instead of `char *p = "sonampulkit";` – Jabberwocky May 15 '17 at 15:25

1 Answers1

0

char *p="sonampulkit";

p - is pointer to string literal, standard of C forbid changing memory: it is undefined behaviour.

knst
  • 523
  • 2
  • 16
  • The second half of your phrase makes not much sense, UB is not a reason but a way to express that something is not defined by the standard. Just remove the word "because". – Jens Gustedt May 15 '17 at 15:30