question on using strstr and strncpy

Posted on 2008-11-05
Last Modified: 2008-11-05

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 = "";

  char* d2 = "";

  char* d3 = "";

  char* pch;

  pch = strstr(d1,"http://");

  strncpy(pch, "xyz", 3);

  printf("\nresult = %s", pch);

  return 0;



Open in new window

Question by:akohan

    Assisted Solution

    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] = "";

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

    LVL 6

    Accepted Solution

    You cannot replace data like that. The d1 is not a buffer only a pointer. If you did:
    char d1[100] = "";
    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:

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
    The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now