首页 > 解决方案 > 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.

标签: cflex-lexer

解决方案


这是不正确的:

printf(lineCount);

的第一个参数printf是一个格式字符串,用于描述您要打印的内容。因为您传递给函数的类型不是它所期望的,所以您调用未定义的行为,在这种情况下会导致崩溃。

如果要打印整数,请使用%d格式说明符。

printf("%d\n", lineCount);

推荐阅读