简体   繁体   English

使用printf在yacc中打印字符串文字标记会导致分段错误

[英]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. 我正在尝试在Yacc中使用char指针打印字符串,但是当我尝试打印时会出现段错误。 The In the lex file it looks like: 在lex文件中,它看起来像:

\"([^"]|\\\")*\" {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: 您的词法分析器返回一个指向包含该字符串的已分配内存1的指针,因此您可能要做的就是复制该指针:

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. 发生分段错误是因为您试图将字符串从strdup分配的内存复制到s指向的内存,但是您从未初始化s指向任何内容。


1 The strdup function calls malloc to allocate exactly enough storage for the string you are duplicating 1 strdup函数调用malloc为要复制的字符串分配足够的存储空间

You must malloc the char *s 您必须分配char * s

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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