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?

5
  • 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. Commented Jan 24, 2023 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 to catch the crash and locate when and where in your code it happens. Commented Jan 24, 2023 at 16:14
  • 1
    You'll need to check argc. Commented Jan 24, 2023 at 16:14
  • 1
    cannot reproduce when supplying valid command line arguments. Commented Jan 24, 2023 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! Commented Jan 24, 2023 at 19:02

1 Answer 1

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`
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, that was exactly the issue, I wasn't passing the right no. of arguments when running the executable!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.