c - Global Variable not reading in Lexer function
问题描述
Working on a compiler, and I want to print out a symbol table. I have a node structure and I need to access the global variable "lineCount". When I try to print it in the idPush function, I get a segmentation fault. My goal is to get the nodes either housed in an array, or linked together, and then print the table.
I have tried to print it elsewhere in the code, but the fault arises. I run a text file that I will include, it is very short just to make sure it is working.
%option noyywrap
%{
#include <stdio.h> /* needed for printf() */
#define YY_DECL int yylex()
#define STRINGMAX 25
struct Node* nodes[100];
int lineCount = 0;
struct Node
{
int data;
char type[STRINGMAX];
char wordv[STRINGMAX];
struct Node *next;
};
void idPush(const char *new_data, char *typel){
// Allocate memory for node
struct Node* new_node = malloc(sizeof(struct Node));
strncpy(new_node->wordv, new_data, STRINGMAX-1);
new_node->wordv[STRINGMAX-1] = '\0';
strncpy(new_node->type, typel, STRINGMAX);
printf("allocated new node space\n");
printf(lineCount);
nodes[lineCount] = new_node;
if(lineCount > 0){
cleanNodes(nodes);
}
getData(new_node);
}
The output for lineCount should be zero as it is the first pass of the code, but I get the segmentation fault.
解决方案
这是不正确的:
printf(lineCount);
的第一个参数printf
是一个格式字符串,用于描述您要打印的内容。因为您传递给函数的类型不是它所期望的,所以您调用未定义的行为,在这种情况下会导致崩溃。
如果要打印整数,请使用%d
格式说明符。
printf("%d\n", lineCount);
推荐阅读
- python - 删除默认帮助命令
- r - 如何从多个回归模型中提取置信区间?
- html - 从 Wordpress 的主菜单中删除项目符号
- javascript - 什么时候虚拟 DOM 比真实 DOM 快?
- python - 将 href 添加到 panda .read_html DF
- reporting-services - SSRS硬编码矩阵的顺序
- firebase - 在没有 android studio 的情况下在本地运行 flutter web 应用程序会引发 firebase 错误
- vue.js - 拖放后的 AG-Grid 数据更新
- go - 如何将“真实”堆栈跟踪放在“stacktrace”键下,而不是“msg”键下?
- javascript - 警告:React.js Web 应用程序中的未知事件处理程序属性“onClick”