打印错误的数据

时间:2018-03-17 19:39:47

标签: c

所以我正在尝试模拟缓存。现在,我为块和集创建了结构并创建了它们的构造函数。当激活缓存集的构造函数时,它会将所有标记和有效位初始化为0.但是,我不断为标记打印出垃圾数据。我可能错误地设置了我的指针,但是我在弄清楚是什么时遇到了问题

#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>


typedef struct
{
uint64_t tag;
unsigned int valid_bit;
}block;

typedef struct
{
unsigned int set_bit;
unsigned int number_of_blocks;
block * blocks;
}cache_set;


block *make_A_BLOCK(uint64_t tg, unsigned int v_b)
{
block *b = malloc(sizeof(block));
b->tag = tg;
b->valid_bit = v_b;
return b;
}
void change_tag(block *b,uint64_t t_g){b->tag = t_g;}
void change_bit(block *b,unsigned int v_b){b->valid_bit = v_b;}
uint64_t return_tag(block *b){ return b->tag;}
unsigned int return_bit(block *b){ return b->valid_bit;}


cache_set *make_A_CACHE_SET(unsigned int s_b, unsigned int n_b)
{
int i;
//uint64_t blank = 0;
cache_set *c_s = malloc(sizeof(cache_set));
c_s->set_bit = s_b;
c_s->number_of_blocks = n_b;
block *blocks = malloc(n_b * sizeof(block));


for (i=0; i < n_b; i++)
{
    blocks[i].tag = 0;
    blocks[i].valid_bit = 0;
}
free(blocks);
return c_s;
}
void print_cache_set(cache_set *c_s)
{
int i;
printf("Number of Cache Sets: %d \r\n",c_s->number_of_blocks);
for (i= 0; i < c_s->number_of_blocks ; i++)
{
    printf("Block %d ",i);
    printf(" Block Tag " "%" PRIu64, return_tag(&(c_s->blocks[i])));
    //printf(" Block Bit %d \r\n", blocks[i].valid_bit);
}
}


int main(void)
{
cache_set *test = make_A_CACHE_SET(0,10);
print_cache_set(test);
printf("done");
return 0;
}

Example

1 个答案:

答案 0 :(得分:0)

在制作cash_set时,您可以分配块并将指针分配给局部变量,然后逐个初始化块。

但是,不是让c_s->blocks指向此初始化的块列表,而是使用free(blocks)取消分配它们。

因此,我建议将free(blocks)替换为c_s->blocks = blocks