1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Reverse a String in C

  1. Oct 2, 2017 #1
    This is what I came up with but I keep getting segmentation fault whenever I run it in linux. Not sure why. Any help would be appreciated. Thanks
    Code (Text):
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    int main(int argc, char** argv)
        int i, childpid;

        for (i = strlen(argv[1]); i >= 0; i--) {
            if (fork() == 0) {

        return 0;
  2. jcsd
  3. Oct 2, 2017 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Homework Helper
    Gold Member
    2017 Award

    This is the position of the terminating null character, not the last character of the string.
  4. Oct 2, 2017 #3
    Thanks for your reply. Pls could you explain further. Not sure what you mean
  5. Oct 2, 2017 #4


    Staff: Mentor

    if you have a 10 character string then valid indexes are 0-9 but strlen returns a 10 so your first loop iteration is referencing an out of bounds element of the string which can result in a segmentation fault but not always.
  6. Oct 2, 2017 #5

    jim mcnamara

    User Avatar

    Staff: Mentor

    Please note: @CAF123 this post is missing a homework template. Since there are answers it will stay as is.
  7. Oct 15, 2017 #6


    User Avatar
    Gold Member

  8. Oct 15, 2017 #7

    jim mcnamara

    User Avatar

    Staff: Mentor

    Thanks for the correction. Since the thread died and @CAF123 straightened me out, let's close this thread.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook