Hi,

I am getting seg fault when trying to run the code. I don't understand where I made a silly mistake. Can someone help me out please

#include<stdio.h>
#include<string.h>
void xstrcpy(char *, char *);

int main()
{
  char *a = "Hello World";
  char *p;
  xstrcpy(a, p);
  return 0;
}

void xstrcpy(char *p, char *q)
{
  while(*p != '\0') {
    *q = *p;
    p++;
    q++;
  }
  *q = '\0';
  printf("Copied String: %s", q);
}

Edited 6 Years Ago by whimsical1987: n/a

Your copying your string over to a NULL pointer...It points to nothing.

Edited 6 Years Ago by gerard4143: n/a

Your copying your string over to a NULL pointer...It points to nothing.

I had changed the code and it works fine now. I have a question

#include<stdio.h>
#include<string.h>
void xstrcpy(char *, char *);

int main()
{
  char str1[] = "Harish Kumar";
  char str2[13];
  xstrcpy(str1, str2);
  printf("Copied String: %s\n", str1);
  return 0;
}

void xstrcpy(char *p, char *q)
{
  while(*p != '\0') {
    *q = *p;
    p++;
    q++;
  }
  *q = '\0';
}

When the printf statement is in the xstrcpy function I cannot print the string in other words it prints null. What is the reason for this ?

*q = '\0';
printf("Copied String: %s\n", q);

Remember your advancing your pointers as you copy into them...Your asking printf to print the end of your string.

Edited 6 Years Ago by gerard4143: n/a

Remember your advancing your pointers as you copy into them...Your asking printf to print the end of your string.

Thank you very much. I didn't think that I had reached the end of the string by incrementing the pointer.

This question has already been answered. Start a new discussion instead.