1
votes

I'm a beginner on C and I have to do an exercise using fork and pipes I have to create a father process which fill in a pipe (with keyboard: stdin) and a child process which have to read the pipe and print it on the screen.

But the execution of this code bring me a "segmentation fault core dump" I have already programmed on Java and this is the equivalent of a "NullpoinerException" right ? I'm looking for some help, because i'm on this problem since 2 hours Thank you

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{

  char* p;
  char* buffer;
  int fd[2];

  pid_t pid = fork();
  pipe(fd);

  //Cas du fils consommateur (Lire dans la pipe, et afficher le contenu a l'ecran ) 
  if (pid == 0)
  {
    close(fd[1]);

    int a;
    do
    {
      a = read(fd[0], buffer, 512);
      //printf("consomateur: %s",  buffer);
    } while (a != 0);

    //Cas du père producteur (remplir la pipe par saisie au clavier)
  }
  else
  {
    close(fd[0]);
    char *adString;

    printf("Enter data \n");
    do
    {
      adString = fgets(buffer, 20, stdin); // on recupere dans un buffer les donneés lues
      write(fd[1], buffer, 512); // on met dans la pipe ce qu'on a mis dans le buffer
    } while (strcmp(adString, "") != 0);

  }

  return 0;
}
1
Regarding the comments in the sources: Most of the guys here do not speak french I assume. - alk

1 Answers

1
votes

The code is missing to allocate memory to the pointer:

char* buffer;

So for example this line:

a = read(fd[0], buffer, 512);

reads to a random address, which most propably causes the segmentation violation.


To fix this you might like to declare buffer like this:

char buffer[512 + 1] = ""; /* Defines buffer to hold 513 bytes and initialise them to 0. */

Referring the + 1: For storing "strings" in C there is an addtional character needed to store the "string"'s 0-termination, marking the end of the "string".


If there were a NULL pointer exception in C it could lead to a segmentation fault. The latter however generally occurs if accessing an invalid memory address, as NULL is.

The core that had been dumped is an image of the process at the moment it died. You can use this core file to inspect the process at this very moment. To do so use gdb:

gbd <program-path/program-file> <core-path/core-file>