Danny
Danny

Reputation: 346

Segmentation Fault in typedef struct

Im trying to make a sintax analyzer using FLEX and C, I implemented a stack, it works fine but when trying to access elements of the structure it returns a Segmentation Fault, I suppouse it has something to deal with the definition of the elements of the structure.

This is parser.h file

#include <stdbool.h>
#ifndef PARSER_H
#define PARSER_H

void error();
bool analisis();

int tokenActual;

#endif

This is a parser.c file

#include <stdio.h>
#include <stdlib.h>

#include "parser.h"
#include "pila.h"
#include "NuT.h"
#include "produccion.h"

extern int yylex();

typedef struct _symbol{
// Indica si es terminal o no terminal
short type;
// Representacion del simbolo en string
char *name;
// Indice del simbolo
short pos;
}sym;

// No terminales
sym *S_ = {NON_TERM,"S",0};
sym *SP_ = {NON_TERM,"SP",1};



//Terminales
sym *OR = {TERM,"v",2};     
sym *PROD = {TERM,"*",3};
sym *SUM = {TERM,"+",4};
sym *INTERR = {TERM,"?",5};
sym *A = {TERM, "a", 6};
sym *B = {TERM,"b",7};
sym *PI = {TERM,"(",8};
sym *PD = {TERM, ")", 9};
sym *EPS = {EPSILON,"ε",10};
sym *EOFF = {TERM,"$",11};

This is the NuT.h:

#include <stdio.h>
#ifndef NUT_H
#define NUT_H
#define TERM 1
#define NON_TERM 2
#define EPSILON 3
#endif

typedef struct _symbol sym;

pila.h file:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#include "NuT.h"

typedef struct _nodo nodo;

typedef struct _Stack Stack;

/* Crea una nueva pila */
Stack* new_stack(void);

/* Permite introducir un elemento a una pila */
void push(Stack* pila, sym* elemento);

/* Permite sacar el primer elemento de la pila */
void* pop(Stack* pila);

/* Indica si una pila no contiene elementos */
bool is_empty(Stack* pila);

/* Permite liberar la memoria que utiliza la pila */
void free_stack(Stack* pila);

/*Permite ver el elemento al tope de la pila*/
sym *top(Stack* pila);

produccion.h file:

#include <stdio.h>

typedef struct _production prod; 

Any thoughts or observations? Thanks

Upvotes: 0

Views: 330

Answers (1)

Lundin
Lundin

Reputation: 214415

The problem is that things like sym *OR = {TERM,"v",2}; isn't valid C, it's just gibberish. You can't initialize a struct pointer with a struct initializer list. It needs to point at an actual object. So just drop the * pointer declaration, why do you need these to be pointers for?

This is why beginners should always compile with a conforming standard C compiler. I recommend using

gcc -std=c11 -pedantic-errors -Wall -Wextra

which would have pointed out the bug for you (unlike default gcc which accepts lots of invalid code). It's much easier to resolve compile-time errors than run-time seg faults.

Upvotes: 1

Related Questions