Segmentation fault (strings, pointers, Linux)

This is a discussion on Segmentation fault (strings, pointers, Linux) within the C Programming forums, part of the General Programming Boards category; I was writing the program for what appeared a fairly simple problem: Print a string in reverse order using recursion. ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    2

    Segmentation fault (strings, pointers, Linux)

    I was writing the program for what appeared a fairly simple problem: Print a string in reverse order using recursion. My code is as follows. The strange thing is that I get Segmentation Fault errors no matter what I do. Any help is greatly appreciated. I'm on Linux, by the way.

    Code:
    /*
    Reverse a string using recursion
    */
    #include <stdio.h>
    
    void rev_string(char *c)
    {    
        if(*c != '\0')
        {
            rev_string(c++);
            printf("%c", *c);
        }
    }
    
    void get_line(char str[])
    {
        int i=0;
        char c;
        
        while(c=getchar() != '\n')
        {    
            str[i++] = c;
        }
        
        str[i] = '\0';
    }
    
    int main()
    {
        char str[100];
        
        get_line(str);
        
        rev_string(str);
            
        printf("\n");
        return 0;
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You are modifying the local copy of c (and passing on the old value!).
    It should be
    Code:
        rev_string(c + 1);
    This is also wrong
    Code:
     while(c=getchar() != '\n')
    it should be
    Code:
     while((c=getchar()) != '\n')
    Otherwise c just gets 0 or 1 depending on whether getchar() returned '\n' or not.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    2
    Oh, wow! Thanks a lot! I didn't realize I was modifying the local variable. Phew!
    Thank you very much, again. Is there a way for me to close this thread?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unable to join two strings due to Segmentation Fault
    By Orange Lozenge in forum C++ Programming
    Replies: 3
    Last Post: 09-15-2011, 05:00 PM
  2. Segmentation fault under linux
    By dennis.cpp in forum C Programming
    Replies: 4
    Last Post: 08-21-2011, 04:30 AM
  3. Segmentation fault when appending to strings (char *)
    By LanguidLegend in forum C Programming
    Replies: 15
    Last Post: 02-24-2011, 07:35 PM
  4. Searching and matching strings: segmentation fault
    By Smola in forum C Programming
    Replies: 18
    Last Post: 07-11-2005, 01:25 AM
  5. segmentation fault - pointers/functions
    By p1c1078 in forum C Programming
    Replies: 15
    Last Post: 04-22-2003, 06:46 PM

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