C programming weird struct setup

I am trying to create this project, and for some reason the program freezes when I run it. It works fine if I comment out the lines of the data cache. but it cannot make makeCache call for two different caches, I don’t know why any experts know C. Im new to c.

   /*
 * main.c
 *
 *  Created on: Sep 16, 2010
 *      Author: TJ
 */
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int tag;
int valid;
int LRU;
int offset;
}directoryBlock;

typedef struct{
int setNumber;
directoryBlock blocks[];
}cacheSet;

typedef struct{
int cacheNumber;
cacheSet *sets[];
}cache;

cache* makeCache(cache *makeMe,int numberOfSets, int blocksPerSet);


int main(void)
{
    int i = 0;
    //cache * temp = makeCache(10,200);
    i = 0;
    int j = 0;
    cache *instructions = malloc(sizeof(cache) + sizeof(cacheSet*));
    cache *data = malloc(sizeof(cache) + sizeof(cacheSet*));
    makeCache(instructions,20,300);
    makeCache(data,20,300);
    for(j=0;j < 20;j++)
            {
                for(i = 0; i < 300;i++)
                {
                    printf("Data From Set %d Block %d, Valid %d, Tag %d, LRU %d, Offset %d\n",j,i
                            ,instructions->sets[j]->blocks[i].valid,instructions->sets[j]->blocks[i].tag
                            ,instructions->sets[j]->blocks[i].LRU,instructions->sets[j]->blocks[i].offset);
                }
            }

    return 0;

}

cache* makeCache(cache *makeMe,int numberOfSets,int blocksPerSet)
{
    int i = 0;
    int j = 0;
    for(j=0; j < numberOfSets;j++)
    {

        cacheSet *newSet = malloc(sizeof(cacheSet) + sizeof(directoryBlock)*blocksPerSet);
        for(i = 0; i < blocksPerSet; i++)
        {
            directoryBlock temp;
            temp.LRU = i*j;
            temp.tag = i*j;
            temp.offset = i*j;
            temp.valid = i;
            newSet->blocks[i] = temp;
        }
        makeMe->sets[j] = newSet;
    }



    return makeMe;
}
+3
source share
2 answers

You do not allocate space for the cacheSet array, you have 20 cache sets, so try this with the addition of "20 *" to your lines:

cache *instructions = malloc(sizeof(cache) + 20 *sizeof(cacheSet*));
cache *data = malloc(sizeof(cache) + 20 * sizeof(cacheSet*));
+3
source

. , , . . , , , . makeCache , . , , makeCache .

- , . sizeof (cache) - . int cacheSet **. cacheSet . ... , , ...

, Thing *t sizof(Thing);

psuedocode:

cache *c = malloc(sizeof(cache))
for 0 to number of cacheSets:
  cacheSet *s = malloc(sizeof(cacheSet))
  for 0 to number of blocks:
    block *b = malloc(sizeof(block))
    //fill in data

JD

0

Source: https://habr.com/ru/post/1765928/


All Articles