c - segmentation fault (core dumped) Error while calling the mknode function -


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 running on input   int mian() {}   giving segementation fault @  char* newnode =(char*)malloc(strlen(token));    node1 *mknode(node1 *left1, node1 *left2, node1* left3,node1* left4,char *token) {    /* malloc 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 error here? plz help

while should run program in debugger find out, these 2 lines culprit:

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

if token null both strlen , strcpy crash.

dereferencing null pointer undefined behavior , in situations cause crash. before dereferencing pointer, or calling function does, need check if pointer null or not.


Comments

Popular posts from this blog

Issues changing the value of an element in an array in matlab -

php - MySQLi binding parameters in a prepared statement doesn't work unless inserted after "WHERE" -

vb.net - Alternative to the T-SQL AS keyword -