I'm trying to print a string with a char pointer in Yacc but when I try it gives me a seg fault. The In the lex file it looks like:
\"([^"]|\\\")*\" {yylval.s = strdup(yytext); yycolumn += yyleng; return(STRINGnumber);}
And I receive the string literal looks like:
//Used to store the string literal
char * s;
//To store it I call
strcpy(s, $1); //Where $1 is the string literal
Whenever I call
printf("%s", s);
It gives me a segmentation fault. Why does it do this and how can it be fixed?
Your lexer returns a pointer to malloced memory1 containing the string, so probably all you need to do is copy the pointer:
s = $1;
more than that is hard to say, as you don't provide enough context to see what you are actually trying to do.
The segmentation fault happens because you're trying to copy the string from the memory allocated by strdup to the memory pointed at by s
, but you never initialize s
to point at anything.
1The strdup
function calls malloc to allocate exactly enough storage for the string you are duplicating