分段错误(core dumped)调用mknode函数时出错

时间:2013-08-13 08:40:04

标签: c yacc

定义YYSTYPE struct node1 *

%令牌INT FLOAT CHAR DOUBLE VOID

开始:声明函数声明1 {$$ = 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”); }

| 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);
}

这里的错误是什么?请帮忙

1 个答案:

答案 0 :(得分:0)

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

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

strcpy(newstr, token);

如果tokenNULL,那么strlenstrcpy很可能会崩溃。

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