简体   繁体   中英

Printing a string literal token in yacc using printf causes a segmentation fault

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 memory 1 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.


1 The strdup function calls malloc to allocate exactly enough storage for the string you are duplicating

You must malloc the char *s

#include <stdlib.h>
#include <string.h>

// in your function
s = malloc(sizeof(char) * (strlen($1) + 1));
strcpy(s, $1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM