bison - YACC - strlen of $1 is 0 although string is there -
i having strange error in program
the structure of yystype is
%union { char *text; node *n; } %token <text> number
and grammar rule is
p: number { cout<<"$1 : "<<$1<<endl; int = 0; while($1[i]) { cout<<"char : "<<$1[i++]<<endl; } $<n>$->left = $<n>$->right = null; char *test1 = new char[strlen($1)]; strcpy(test1, $1); cout<<"len : "<<strlen($1)<<"test1 : "<<test1<<endl; char *lolz = strdup($1); cout<<"dup : "<<((uint64_t)lolz)<<' '<<((int)lolz[1])<<" : dup"<<endl; $<n>$->data = string($1); cout<<"nd : "<<$<n>$->data<<endl; print_tree($<n>$); } ;
i can print contents of $1, when strlen($1), returns 0 length causing strdup , string initialisation fail.
output:
$1 : 65301 char : 6 char : 5 char : 3 char : 0 char : 1 len : 0test1 : dup : 26935504 0 : dup segmentation fault (core dumped)
am missing obvious here?
when execute:
$<n>$->left = $<n>$->right = null;
what suppose value of $<n>$
is? have assigned address of node
object?
to save time: haven't assigned think of uninitialised pointer; dereferencing uninitialised pointer undefined behaviour , corresponds see.
but analysis not quite accurate.
the bison-generated parser initialises $$
$1
prior executing action. in case, $1
union text
member has been assigned to, using n
member (a different) ub. result same in common compilers more predictable: suppose left
element of node
@ offset 0, assignment above overwrites first 16 bytes of character string zeros (8 if have 32-bit architecture). that's buffer overrun, if doesn't segfault, end result first byte of $1
0, hence return value of strlen
. (when try use data
element, segfault, apparently, presumably because not initialised std::string
. using zero-length c-string not problem either strdup
or std::string
constructor.)
moral: never assign through pointer if don't know points to.
by way, strcpy
test1 buffer overrun of 1 byte. seem have gotten away time it's bad habit.
Comments
Post a Comment