Replacing chars in Pointer String results in Segfault

This is a discussion on Replacing chars in Pointer String results in Segfault within the C Programming forums, part of the General Programming Boards category; I've written a function which I want to replace all the spaces in a string with '-'. I get a ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    9

    Unhappy Replacing chars in Pointer String results in Segfault

    I've written a function which I want to replace all the spaces in a string with '-'. I get a Segmentation Fault when I run it. However, using gdb with a break point set in the function and stepping through it, it works fine.
    Code:
    #include <stdio.h>
        
    int replace (char *cat);
        
    main()
    {
        char *s1 = "The cat sat ";
        printf("The string before replacement is: \n");
        printf("%s\n", s1);
        
        int n = replace(s1);
        printf("Number of replaced spaces: %d\n", n);
        printf("The string after replacement is: \n");
        printf("%s\n", s1);
    }
        
    int replace (char *cat)
    {
        int length = strlen(cat);
        int r = 0;
        int i;
        
        for (i=0; i < length; i++)
        {
            printf("cat[%d]: %c\n", i, cat[i]);
            if (cat[i] == ' ')
            {
                cat[i]='-';  // results in Seg Fault (set break point at beginning of line)
                r++;
            }
        }
        
        return r;
    }
    Thanks in advance!

  2. #2
    Registered User
    Join Date
    Mar 2003
    Posts
    9

    Smile

    Thanks for your help!
    Does this mean that any time you set a char* to a string constant, it is not writable? Because in the case of my replace function, it has an argument which is a char* and this is writable.

  3. #3
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    I think to transform it "writeable" you'll need to allocate memory for it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21