0

定义 YYSTYPE 结构节点1 *

%token INT FLOAT CHAR DOUBLE VOID

开始:声明函数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); }
;

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

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

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

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

| 无效 {$$ = 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);
}

这里有什么错误?请帮助

4

1 回答 1

0

虽然你真的应该在调试器中运行你的程序来找出它,但这两行可能是罪魁祸首:

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

strcpy(newstr, token);

如果两者都是token,并且很可能会崩溃。NULLstrlenstrcpy

取消引用NULL指针是未定义的行为,并且在大多数情况下会导致崩溃。在取消引用指针或调用执行此操作的函数之前,您需要检查指针是否NULL存在。

于 2013-08-13T08:43:32.403 回答