I am writing a compiler project. I created an AST tree, where every node is defined by structure:
typedef struct node {
char type[10];
char *string;
int number_of_children;
struct node *children[];
} node;
I wanted to create an array of symbols of undefined length. I created structure, to store name of the symbol and it's address in the memory:
typedef struct symbol {
char *name;
int address;
} symbol;
and then I created array of undefined length:
symbol *symbols_table[];
I created function to add new symbol:
void add_symbol(node *p) {
symbols_table[number_of_symbols] = malloc(sizeof(symbol));
symbols_table[number_of_symbols]->name = malloc(sizeof(p->string));
strcpy(symbols_table[number_of_symbols]->name, p->string);
symbols_table[number_of_symbols]->address = memory_pointer;
memory_pointer++;
number_of_symbols++;
}
where p is node from the AST tree and memory_pointer is needed to give address in the memory to each symbol.
And here is the problem. When I want to add only 2 symbols to the symbols_table everything is working fine. But when I want to add 3 and more it gives segmentation fault. Do you have any ideas, why is it happening?
symbol *symbols_table[]creates? If you think it creates an array that can hold any number of elements you might choose to store in it, you are sadly mistaken.symbol *symbols_table[];, if done globally, should make the compiler issue a warning, if given local to a function it should not even compile. Take warnings serious.