0
votes

define YYSTYPE struct node1 *

%token INT FLOAT CHAR DOUBLE VOID

start: Declaration Function Declaration1 {$$ = mknode($1, $2, $3,NULL,0);}

|Declaration Function             {$$=mknode($1,$2,NULL,NULL,0);}   
        
| Declaration                 {$$ =mknode($1,NULL,NULL,NULL,0); }

| Function                {$$ =mknode($1,NULL,NULL,NULL,0); }
;

Declaration1 :Function           {$$ =mknode($1,NULL,NULL,NULL,NULL); }
;


Function: 

Type ID '(' ArgListOpt ')' CompoundStmt         {$$ = mknode($1,$2,$4,$6,NULL); }
;

Type: INT {$$ = mknode(NULL,NULL,NULL,NULL,"INT"); }

| FLOAT {$$ = mknode(NULL,NULL,NULL,NULL,"FLOAT"); }

| CHAR {$$ = mknode(NULL,NULL,NULL,NULL,"CHAR"); }

| DOUBLE {$$ = mknode(NULL,NULL,NULL,NULL,"DOUBLE"); }

| VOID {$$ = mknode(NULL,NULL,NULL,NULL,"VOID"); }

;

CompoundStmt: '{' StmtList '}'      {$$ =$2; }
;

StmtList: StmtList Stmt            {$$ = mknode($1,$2,NULL,NULL,NULL); }

|                   {$$=mknode(NULL,NULL,NULL,NULL,NULL);}
;

when i am running this on the input 

int mian()
{}


it is giving segementation fault at

char* newnode =(char*)malloc(strlen(token));



node1 *mknode(node1 *left1, node1 *left2, node1* left3,node1* left4,char *token)
{

  /* malloc the node */

  node1 *newnode = (node1 *)malloc(sizeof(node1));



  char *newstr = (char *)malloc(strlen(token));

  strcpy(newstr, token);



  newnode->left1 = left1;

  newnode->left2 = left2;

newnode->left3 = left3;

  newnode->left4 = left4;

  newnode->token = newstr;

  return(newnode);
}

what is the error here? plz help

1
i have replaced o with NULL still not workinguser123
@swati... What you are getting in token??? Please edit token value.someone
@Krishna i have added the above rules for the tokenuser123
after the removal of segmentation fault now it is showing parsing failed while iam trying to run the program..but before this there was no parsing error..i have parsed the complete program before writing the actions and it was successfully parsing..but now its not..what could be the erroruser123
~$ yacc c.y~$ lex c.l ~$ gcc y.tab.c -ll -ly ~$ ./a.out int main() {} 3 : syntax error Parsing faileduser123

1 Answers

0
votes

While you should really run your program in a debugger to find it out, these two lines are a likely culprit:

char *newstr = (char *)malloc(strlen(token));

strcpy(newstr, token);

If token is NULL then both strlen and strcpy will most likely crash.

Dereferencing a NULL pointer is undefined behavior and will in most situations cause a crash. Before dereferencing a pointer, or calling a function that does, you need to check if the pointer is NULL or not.