• C

question on using strstr and strncpy


I'm using following code but in runtime I get a segmentation fault message.  I'm trying to learn how find a substring in a string and replace with something or "".


#include <stdio.h>
#include <string.h>
int main(void)
  char* d1 = "http://www.test.com";
  char* d2 = "https://www.test.com";
  char* d3 = "https://test.com";
  char* pch;
  pch = strstr(d1,"http://");
  strncpy(pch, "xyz", 3);
  printf("\nresult = %s", pch);
  return 0;

Open in new window

Who is Participating?
WerrockConnect With a Mentor Commented:
You cannot replace data like that. The d1 is not a buffer only a pointer. If you did:
char d1[100] = "http://www.test.com";
char *pch  = strstr(d1,"http://");
strncpy(d1, "xyz", 3);
printf("\nresult = %s", pch);

It would "work" but not as intended since its not a true replace since your only overrideing some data in the buffer, it the string length is different this wont work. There is no function call to do it right away and you need to copy or move some data for it. Read more about it here:
dlinvillConnect With a Mentor Commented:
You are defining d1 as a pointer to a constant character string.  You can't then copy over it.

Try defining d1 like:    char d1[99] = "http://www.test.com";

This gives you an array of characters that you can then use as the destination in strncpy

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.