Reverse a String in C - Solve Segmentation Fault

  • Thread starter Thread starter carl123
  • Start date Start date
  • Tags Tags
    Reverse String
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
carl123 said:
i = strlen(argv[1])
This is the position of the terminating null character, not the last character of the string.
 
  • Like
Likes carl123
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.
 
Please note: @CAF123 this post is missing a homework template. Since there are answers it will stay as is.
 
Thanks for the correction. Since the thread died and @CAF123 straightened me out, let's close this thread.
 

Similar threads

Replies
2
Views
10K
Replies
10
Views
2K
Replies
2
Views
2K
Replies
8
Views
2K
Replies
7
Views
2K
Replies
2
Views
2K
Back
Top