• 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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

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:

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.