我试图在Yacc中打印一个带有char指针的字符串,但当我尝试时,它会给我一个seg错误。在lex文件中,它看起来像:
"([^"]|\")*" {yylval.s = strdup(yytext); yycolumn += yyleng; return(STRINGnumber);}
我收到的字符串文字看起来像:
//Used to store the string literal
char * s;
//To store it I call
strcpy(s, $1); //Where $1 is the string literal
每当我打
printf("%s", s);
它给我一个分段错误。它为什么会这样做,如何修复?
您的lexer返回一个指向包含字符串的mallocated内存1的指针,所以您可能只需要复制指针:
s = $1;
更重要的是,很难说,因为你没有提供足够的上下文来了解你实际想做什么
分段错误的发生是因为您试图将字符串从strdup分配的内存复制到s
指向的内存,但从未将s
初始化为指向任何东西。
1strdup
函数调用malloc为正在复制的字符串分配足够的存储空间
您必须对字符的进行malloc
#include <stdlib.h>
#include <string.h>
// in your function
s = malloc(sizeof(char) * (strlen($1) + 1));
strcpy(s, $1);