Home > other >  Error message "segmentation fault (core dumped)"
Error message "segmentation fault (core dumped)"

Time:01-25

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?

CodePudding user response:

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`
  • Related