(I know using global variables isn't generally a good idea, but the way my lab is structured leads me to believe it's required.)
Basically I'm supposed to simulate a cache, and I've decided to make my cache an array of linked lists, where each node is a struct called "block" which contains information such as the address and a valid indicator.
In my original code, I had the (working) declaration:
struct block **cache = malloc(sizeof(struct block)*numofsets);
But since looking at the file I have to fit my cache-related functions into, I realized none of the functions that need to use the cache would have it in their scope, and I can't edit them, so I decided the only way to avoid this would be to increase the scope of my cache to become a global.
The main issue came when I put the declaration struct block **cache;
outside of main, with *cache = malloc(sizeof(struct block)*numofsets);
within the main. When I ran my code, it had a seg fault. I used print statements to find where the seg fault was coming from, and the malloc
line is the culprit.
I'm not really sure how to fix this problem. Since I'm using C, I can't malloc
the global outside of the main function since it give me an "initializer not constant" error, and fiddling with the pointers have gotten me worse errors. And what's more, this declaration/instantialization, to me, seems to be nearly identical in terms of structure to what it was before.
What is causing this instantialization to not work? Is there any way I can fix it, or is my implementation doomed?
Edit: I've been fooling around a little more with it, and I've realized the issue is not that it's a global variable, but that for some reason separating the declaration from the initialization gives me a seg fault. Not sure why this would be.