Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global pointer in C

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

like image 766
CSCSCS Avatar asked Dec 04 '25 17:12

CSCSCS


1 Answers

It looks like you are trying to malloc when you should just use global data. You could try

struct conscell globalEnvironment;

Just remember to never free it.

If you need to have a pointer handle so you can push cells on the list:

struct conscell _globalEnvironment;
List globalEnvironment = &_globalEnvironment;

Still, remember to never free _globalEnvironment.

like image 140
kmkaplan Avatar answered Dec 06 '25 07:12

kmkaplan