Segmentation fault when I pipe stdout to my program

I don't know if I have to tell it again, but english is not my native language and I'm not a very good student, I've seen you are able to correct my message so it's fine but I'd like to apologize once again.

Here is the deal, I have a program, which convert a given graph passed in argument to Dimacs format that I'll store in a .cnf file. (We use it to solve it with a SAT-solver)

He's perfectly working when I use it by myself, so I'd like to have another program, graph_generator, that I'll pipe into myprogram to have random graphes.

I've made my graph_generator program, and he correctly prints graph at the format I want, so I've tried to do basically ./graph_generator | ./myprogram but I instantly get a segmentation fault, I can't see why, graph_generator returns exactly what it's expected, and when I want to use a debugger, I don't see how it's possible knowing that I pipe a result, when I copy paste the result of graph_generator myprogram correctly generates my .cnf file.

I don't know where the problem could come from, I have a theory but it's a bit lame, it's that the stdout of graph_generator, once piped myprogram considers the space as an argument and there is the problem. Anyone could help me please?

int main (int argc, char* argv[]){
  graph* mygraph;
  int taille, nbEdge;
  int i;
  FILE* resultat;


  printf("mark 1");
  taille = atoi(argv[1]);
  nbEdge = atoi(argv[2]);
  printf("mark 2");
  mygraph = build_empty_graph(taille);
  for(i = 3; i < argc; i+= 2)
    add_edge(atoi(argv[i]), atoi(argv[i+1]), mygraph);

  resultat = fopen("resultat.cnf", "w");
  write_result_comments(resultat);
  write_result_header(resultat, mygraph);
  write_first_stack(resultat, mygraph);
  write_second_stack(resultat, mygraph);
  fclose(resultat);

  return 0;
}

Here is the main of myprogram, when I use it with the pipe, the message "mark1" doesn't even appears

Upvotes: 0

Views: 392

Answers (1)

stark
stark

Reputation: 13189

It is segfaulting because you don't check argc and are passing no values as arguments. Please note that stdin is a separate stream from the arguments in argv.

Best way to fix this is to build up hierarchically:

tokenizer: read stdin in a loop with getchar until you get to whitespace (space, tab or newline).

parser: atoi is fine, since you only pass ints.

state machine: first two args to taille and nbEdge, rest in pairs (x, y) to call the program. Maybe use a switch statement and a state variable in a loop.

program: the rest of your program pretty much as is.

Upvotes: 1

Related Questions