0

I'm trying to run the following C program:

/*
 * Illustrates system call fork
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (
  int argc,
  char *argv[]
  )
{
  int tC, tF;
  pid_t pid;

  tC = atoi (argv[1]);
  tF = atoi (argv[2]);

  fprintf (stdout, "Main  :                  ");
  fprintf (stdout, "PID=%d; My parent PID=%d\n",
    getpid(), getppid());

  pid = fork();
  if (pid == 0){
    // Child
    sleep (tC);

    fprintf(stdout, "Child : PIDreturned=%d    ", pid);
    fprintf (stdout, "PID=%d; My parent PID=%d\n",
      getpid(), getppid());
  } else {
    // Father
    sleep (tF);

    fprintf(stdout, "Father: PIDreturned=%d ", pid);
    fprintf (stdout, "PID=%d; My parent PID=%d\n",
      getpid(), getppid());
  }

  return 0;
}

I'm able to compile the code, but when I try to run the executable file I get a "segmentation fault (core dump)" error message.

Can anyone tell me what is causing such issue and how to fix it?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 5
    You are not checking if the user supplied any arguments. If fewer than 2 arguments are supplied to the program, it'll do `atoi` on `argv` out of bounds. – Ted Lyngmo Jan 24 '23 at 16:11
  • 2
    How do you run your program? Are you sure you pass two arguments? Always check `argc` *first* before using anything other than `argv[0]` (which technically could be `NULL` as well). Other than that, create a debug build (add the `-g` flag when building) and use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to catch the crash and locate when and where in your code it happens. – Some programmer dude Jan 24 '23 at 16:14
  • 1
    You'll need to check `argc`. – tadman Jan 24 '23 at 16:14
  • 1
    [cannot reproduce](https://godbolt.org/z/71Kdz47zn) when supplying valid command line arguments. – yano Jan 24 '23 at 16:17
  • thx!! @Someprogrammerdude the issue was exactly that! I wasn't passing the right no. of arguments when running the executable. Also, thx for the tip, I'll make sure to check argc in the code! – Marco Sperindeo Jan 24 '23 at 19:02

1 Answers1

5

You are not checking if the user supplied any arguments. If fewer than 2 arguments are supplied to the program, it'll do atoi on argv out of bounds (which has undefined behavior and the program may crash as a result).

I suggest that you check it directly at start of main. Example:

int main(int argc, char* argv[]) {
    if(argc != 3) {
        fprintf(stderr, "USAGE: %s child-sleeptime parent-sleeptime\n", argv[0]);
        return 1;
    }

    // ... the rest of `main`
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108