Reverse a String in C - Solve Segmentation Fault

  • Context: Undergrad 
  • Thread starter Thread starter carl123
  • Start date Start date
  • Tags Tags
    Reverse String
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
carl123
Messages
55
Reaction score
0
1.JPG

2.JPG

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:
#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) {
            printf("%c\n",argv[1][i]);
            break;
        }
    }

    return 0;
}
 
Mathematics news on Phys.org
Orodruin said:
This is the position of the terminating null character, not the last character of the string.
Thanks for your reply. Pls could you explain further. Not sure what you mean
 
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.