使用 printf 在 yacc 中打印字符串文字标记会导致分段错误
Printing a string literal token in yacc using printf causes a segmentation fault
我试图在 Yacc 中打印一个带有 char 指针的字符串,但是当我尝试时它给了我一个段错误。在 lex 文件中它看起来像:
\"([^"]|\\")*\" {yylval.s = strdup(yytext); yycolumn += yyleng; return(STRINGnumber);}
我收到的字符串文字如下所示:
//Used to store the string literal
char * s;
//To store it I call
strcpy(s, ); //Where is the string literal
每当我打电话
printf("%s", s);
它给我一个分段错误。为什么要这样做,如何解决?
您必须 malloc char *s
#include <stdlib.h>
#include <string.h>
// in your function
s = malloc(sizeof(char) * (strlen() + 1));
strcpy(s, );
你的词法分析器returns指向包含字符串的分配内存1的指针,所以你可能需要做的就是复制指针:
s = ;
很难说更多,因为您没有提供足够的上下文来了解您实际尝试做的事情。
发生分段错误是因为您试图将字符串从 strdup 分配的内存复制到 s
指向的内存,但您从未初始化 s
以指向任何内容。
1strdup
函数调用 malloc 为您正在复制的字符串分配恰好足够的存储空间
我试图在 Yacc 中打印一个带有 char 指针的字符串,但是当我尝试时它给了我一个段错误。在 lex 文件中它看起来像:
\"([^"]|\\")*\" {yylval.s = strdup(yytext); yycolumn += yyleng; return(STRINGnumber);}
我收到的字符串文字如下所示:
//Used to store the string literal
char * s;
//To store it I call
strcpy(s, ); //Where is the string literal
每当我打电话
printf("%s", s);
它给我一个分段错误。为什么要这样做,如何解决?
您必须 malloc char *s
#include <stdlib.h>
#include <string.h>
// in your function
s = malloc(sizeof(char) * (strlen() + 1));
strcpy(s, );
你的词法分析器returns指向包含字符串的分配内存1的指针,所以你可能需要做的就是复制指针:
s = ;
很难说更多,因为您没有提供足够的上下文来了解您实际尝试做的事情。
发生分段错误是因为您试图将字符串从 strdup 分配的内存复制到 s
指向的内存,但您从未初始化 s
以指向任何内容。
1strdup
函数调用 malloc 为您正在复制的字符串分配恰好足够的存储空间