I am new to C and I am currently implementing a Scheme interpreter in C. I am close to the end but a problem is bothering me which I have not been able to tackle yet.
I want a “globalEnvironment” pointer to a struct which stays throughout the time the program runs and gets modified too (not a constant).
/****************************************************************
Creates the List as a pointer to the conscell structure
*/
typedef struct conscell *List;
/****************************************************************
Creates a conscell structure, with a char pointer (symbol) and two pointers to
* conscells (first and rest)
*/
struct conscell {
char *symbol;
struct conscell *first;
struct conscell *rest;
};
List globalEnvironment;
/****************************************************************
Function: globalVariables()
--------------------
This function initializes the global variables
*/
void globalVariables() {
globalEnvironment = malloc(sizeof (struct conscell));
globalEnvironment->symbol = NULL;
globalEnvironment->first = NULL;
globalEnvironment->rest = NULL;
}
As you can see “List” is a pointer to a conscell structure. So all I want is the globalEnvironment List to be global.
The problem is that I cannot do malloc there. If I try the following:
List globalEnvironment = malloc(sizeof (struct conscell));
instead of just “List globalEnvironment;” it gives an error that “initialiser element is not a constant”
To tackle this situation, I created a new function “globalVariables” which runs at the beginning of the program, initialises globalEnvironment and allocates it memory.
It is not working as I expected though and I keep getting segmentation fault errors for other functions that I have not written here to keep it simple.
Is there another, simpler, way to declare a pointer (not constant) to a structure in C?
Hope someone can help,
Thank you
It looks like you are trying to
mallocwhen you should just use global data. You could tryJust remember to never
freeit.If you need to have a pointer handle so you can push cells on the list:
Still, remember to never
free_globalEnvironment.