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);
}

Recommended Answers

All 4 Replies

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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.