0

For the spell check program, we have to read the dictionary from a file into a data structure (e.g. linked list, hash table with linked lists, a try). However, we have to do this within the function bool load(). This function is outside of the main function however, so all the local variables (including any pointers or structs) created within load will disappear when load is done.

We can't alter the function headers, so we can't pass in or return any pointers, that might allow us to change data in ways that last beyond the end of the load() function.

Maybe we would use global variables, but this would require us to know ahead of time what variables/structs we want. However, when we go through the dictionary, we will want to be dynamically creating nodes.

How are we able to have variables (whether structs, pointers, ints, etc) that last beyond the implementation of load()?

0

I'm going to take a shot at partially answering my own question. In dictionary.c, we can declare a global variable that will be able to be accessed by speller.c. This global variable can be the root of, say, a try or a hash table. After load() is done its work, we return to speller.c.

Speller.c or the other functions in dictionary .c can then trace the pointers in this global root to find the rest of the dictionary data.

Any nodes made using malloc will have their memory on the heap rather than the stack (I believe?). This means that all of these nodes, which are structs, are stored in the heap and are not going to be written over by new local variables in other functions. The relevant pointers are also stored inside the note structs, such that they are also kept on the heap.

Essentially, the answer is that dynamic memory allocation stores data in the heap rather than the stack. Someone please clarify if I am wrong about this answer.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .