I am trying to write a simple HTTP request parser for a school assignment but I have this segmentation fault that I can t get rid of. I think that my production rules are ok. I have executed bison with tracing enabled and it always produces a segfault at part where it parses my header:
Reducing stack by rule 9 (line 59):
$1 = token ID ()
$2 = token COLON ()
$3 = token STRING ()
[4] 36661 segmentation fault (core dumped) ./problem1 < input.txt
这里是我的请求书。
%option noyywrap
%{
#include<stdio.h>
#include "request.tab.h"
char *strclone(char *str);
%}
num [0-9]+(.[0-9]{1,2})?
letter [a-zA-Z]
letternum [a-zA-Z0-9-]
id {letter}{letternum}*
string "[^"]*"
fieldvalue {string}|{num}
%%
(GET|HEAD|POST|PUT|DELETE|OPTIONS) { yylval = strclone(yytext); return METHOD; }
HTTP/{num} { yylval = strclone(yytext); return VERSION; }
{id} { yylval = strclone(yytext); return ID; }
"/" { return SLASH; }
"
" { return NEWLINE; }
{string} { yylval = strclone(yytext); return STRING; }
":" { return COLON; }
[
]+ ;
. {
printf("Unexpected: %c
Exiting...
", *yytext);
exit(0);
}
%%
char *strclone(char *str) {
int len = strlen(str);
char *clone = (char *)malloc(sizeof(char)*(len+1));
strcpy(clone,str);
return clone;
}
and my request.y file:
%{
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define YYSTYPE char*
extern int yylex();
extern int yyparse();
extern FILE* yyin;
void yyerror(const char* s);
%}
%token METHOD
%token SLASH
%token VERSION
%token STRING
%token ID
%token COLON
%token NEWLINE
%%
REQUEST: METHOD URI VERSION NEWLINE HEADERS {
printf("%s %s", $1, $2);
}
;
URI: SLASH DIR {
$$ = (char *)malloc(sizeof(char)*(1+strlen($2)+1));
sprintf($$, "//%s", $2);
}
;
DIR: ID SLASH {
$$ = (char *)malloc(sizeof(char)*(strlen($1)+2));
sprintf($$, "%s//", $1);
}
|ID {
$$ = $1;
}
| {
$$ = "";
}
;
HEADERS: HEADER {
$$ = $1;
}
|HEADER NEWLINE HEADERS {
$$ = (char *)malloc(sizeof(char)*(strlen($1)+1+strlen($3)+1));
sprintf($$, "%s
%s", $1, $3);
}
|{
$$ = "";
}
;
HEADER: ID COLON STRING {
$$ = (char *)malloc(sizeof(char)*(strlen($1)+1+strlen($2)+1));
sprintf($$, "%s:%s", $1, $3);
}
;
%%
void yyerror (char const *s) {
fprintf(stderr, "Poruka nije tacna
");
}
int main() {
yydebug = 1;
yyin = stdin;
do {
yyparse();
} while(!feof(yyin));
return 0;
}
这里也是我的投入内容。
GET / HTTP/1.1
Host: "developer.mozzila.org"
Accept-language: "fr"