0

I am not sure why this does not work. I am a bit confused about the typedef's

typedef struct cache_line {
    int valid;
    int tag;
    int usage;
} cache_line_t;

typedef cache_line_t* cache_set_t;

typedef cache_set_t* cache_t;

void init() {
  S = 2 << (s-1);
  B = 2 << (b-1);

  cache = malloc(sizeof(cache_set_t*) * S);
  for(int i = 0; i < S; i++) {
    cache[i] = malloc(sizeof(cache_line_t*) * E);
    for(int j = 0; j < E; j++) {
      cache[i][j]->valid = 0;
      cache[i][j]->tag = 0;
      cache[i][j]->usage = 0;
    }
  }
}

Compiling gives an error with the ->'s

s, b, S, B, and E are ints. cache is defined above as a cache_t. I am trying to make an array of S sets which are arrays of E lines.

Any help is greatly appreciated

Dave Jones
  • 67
  • 5
  • 3
    Get out of the habit of using typedefs for pointers, it just makes things more confusing. – Barmar Nov 14 '19 at 03:07
  • Where is the declaration of `cache`? – Barmar Nov 14 '19 at 03:09
  • https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers – Barmar Nov 14 '19 at 03:09
  • It's just `cache_t cache;` – Dave Jones Nov 14 '19 at 03:11
  • See [Is it a good idea to typedef pointers?](https://stackoverflow.com/questions/750178/) — TL;DR generally No, with exceptions for pointers to functions. Note that the global variables `s`, `b`, `S`, `B`, and `E` should probably not be globals; they could be stored in a structure along with the pointer to (pointer to) the cache line data. You could pass the `s` and `b` values to the `init()` function (which should be named `cache_init()`). The global variable `cache` is probably a bad idea; why not return the value from `init()`. Then you can have different caches with different sizes, etc. – Jonathan Leffler Nov 14 '19 at 03:12
  • Then your `sizeof` is wrong. You need to use the size of the object it points to, so it should be `cache = malloc(sizeof(cache_set_t) * S)` – Barmar Nov 14 '19 at 03:13

1 Answers1

2

Change cache = malloc(sizeof(cache_set_t*) * S); to cache = malloc(sizeof *cache * S);, because you need space for S objects that cache points to, not S objects of the type that cache is.

Change cache[i] = malloc(sizeof(cache_line_t*) * E); to cache[i] = malloc(sizeof *cache[i] * E);, for the same reason.

Change:

  cache[i][j]->valid = 0;
  cache[i][j]->tag = 0;
  cache[i][j]->usage = 0;

to:

  cache[i][j].valid = 0;
  cache[i][j].tag = 0;
  cache[i][j].usage = 0;

because cache[i][j] is a structure, not a pointer to a structure.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312