C 阵列分段故障中的数据访问

C 阵列分段故障中的数据访问,c,pointers,memory,dynamic-memory-allocation,C,Pointers,Memory,Dynamic Memory Allocation,我在程序中遇到了一个分段错误,我很确定这是一个愚蠢的错误!当我试图访问我的结构数组中的数据时,我得到了一个segementation错误 struct block { int validBit; int tag; unsigned long data; }; typedef struct block block_t; struct set{ bloc

我在程序中遇到了一个分段错误,我很确定这是一个愚蠢的错误!当我试图访问我的结构数组中的数据时,我得到了一个segementation错误

struct block {
  int validBit;                        
  int tag;                            
  unsigned long data;              
};
typedef struct block block_t;

struct set{
 block_t *blocks;
 int tst;
};
typedef struct set set_t;

struct cache{
  //bunch of variables I have left out for this question

  set_t *set;
};
typedef struct cache cache_t;
cache->set[1].blocks[0].validBit = 3; // This works
cache->set[1].blocks[0].tag = 3; //does not work
因此,分配给它们的内存是

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

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

cache->set->blocks = malloc(2 * sizeof(*cache->set->blocks));
if(cache->set->blocks == NULL){
 fprintf(stdout,"Could not allocate memory for cache->set->blocks!");
}
缓存包含一个包含16个元素的集合数组。cache->set保存一个包含2个元素的块数组

当我试图设置块结构中变量的值时,会出现分段错误

cache->set[0].blocks[0].tag = 1; //This works
cache->set[0].blocks[1].tag = 2; //This works
cache->set[1].blocks[0].tag = 3; //Segmentation fault
编辑:看起来块内的变量“tag”有问题。如果在集合[1]中为validbit赋值,则不会产生分段错误

struct block {
  int validBit;                        
  int tag;                            
  unsigned long data;              
};
typedef struct block block_t;

struct set{
 block_t *blocks;
 int tst;
};
typedef struct set set_t;

struct cache{
  //bunch of variables I have left out for this question

  set_t *set;
};
typedef struct cache cache_t;
cache->set[1].blocks[0].validBit = 3; // This works
cache->set[1].blocks[0].tag = 3; //does not work
那么这似乎是tag变量的问题?对我来说毫无意义


提前感谢:)

您没有为超出集合[0]的“块”分配内存

大致来说,您应该按照以下思路做一些事情:

cache = malloc(sizeof *cache);
cache->set = malloc(num_sets * sizeof *cache->set);
for (i = 0; i < num_sets; i++) {
    cache->set[i].blocks = malloc(...);
}
cache=malloc(sizeof*cache);
cache->set=malloc(num_sets*sizeof*cache->set);
对于(i=0;i设置[i]。块=malloc(…);
}

cache=malloc(sizeof(*cache);
处出现语法错误。您只为
cache->set[0]分配内存。blocks
cache->set[1]。blocks
是一个垃圾指针。很抱歉,由于某些原因,从我的代码中复制粘贴时没有获取cache的typedef。它在中编辑。为什么我要用sizeof(cache)而不是(*cache)?在前面的一个问题中,我用同样的代码问了我,我被告知sizeof(cache)是错误的,应该是sizeof(*cache)。想解释一下吗?谢谢:)我从来没有说过关于
sizeof(cache)
??是其他人说malloc(sizeof(chace))是错误的,我应该使用malloc(sizeof(*cache))相反,两个人在告诉我不同的事情,只是想知道什么是真正正确的?谢谢:)非常感谢!结果是我对这门学科的知识太少了!非常感谢你!