Reverse a String in C - Solve Segmentation Fault

  • Level: Undergrad 
  • Thread starter carl123
  • Start date
  • Tags Tags
    Reverse String
6 replies · 2K views · last reply
carl123
Messages
55
Reaction score
0
Text of a programming assignment: write a C/C++ program string_invert that reverses a command-line string using fork, with two constraints on characters output and forks per process.

Printed note in bold 'Note:' warning against creating processes inside a loop, advising checking fork logic, using ps -a to monitor, and kill -9 <pid> to abort runaway processes.

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;
}
 
carl123 said:
i = strlen(argv[1])
This is the position of the terminating null character, not the last character of the string.
 
  • Like
Likes   Reactions: 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.