0

Im trying to make a cache with C, but I'm having an issue with allocating memory at the last array of a structure

struct block{
 int validBit;
 char *tag;

}    

typedef struct block block_t;

Struct set{
 block_t *blocks;
}

typedef struct set set_t;

Struct cache{
  //Some other variables but not important for this question
  set_t *set;
}

typedef struct cache cache_t;

So I allocate memory for cache like this in a setupCache() function

cache_t *cache = NULL;

cache = malloc(sizeof(cache));
if(cache == NULL){
 fprintf(stdout, "Could not allocate memory for cache!");
}

This works fine, now I allocate memory of an array of struct set with 16 elements

cache->set = malloc(16 * sizeof(cache->set));
//same error check as above here, just left our for precision of question

This also works, now I allocate memory for the block array within the set

for(i = 0; i < 16; i++){
cache->set->blocks = malloc(2 * sizeof(cache->set->blocks));

Again this works, but here the trouble comes

cache->set->blocks[i] = malloc(sizeof(block_t));

This give me an error: incompatible types when assigning to type ‘block_t’ from type ‘void *’

Not really sure what I'm doing wrong, probably something silly.

This is how it should be: The cache holds an array of set struct with 16 elements, each of these set elements should have an array of block struct with 2 elements.

Hope any of you can help me!

1 Answer 1

2

First and foremost, in your code, your memory allocation is wrong. You're providing wrong size altogether for every memory allocation. For example,

cache = malloc(sizeof(cache));

should be

cache = malloc(sizeof(*cache));

and likewise.

After that, cache->set->blocks[i] is of type block_t, not block_t *, so this does not need to be allocated memory dynamically, at all.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Thank you very much for your reply! I'm a bit confused though. Could you explain why I should provide the size with *cache instead of cache? Also, cache->set->blocks should be an array of 2 elements of the struct block_t. Shouldn't those be allocated memory?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.