【问题标题】:Accessing data in array segmentation fault在数组分段错误中访问数据
【发布时间】:2017-03-13 00:47:28
【问题描述】:

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

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_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->sets 包含一个包含 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”似乎有问题。如果我在 set[1] 中为 validbit 赋值,它不会产生分段错误。

cache->set[1].blocks[0].validBit = 3; // This works
cache->set[1].blocks[0].tag = 3; //does not work

所以这似乎是标签变量的问题?对我来说毫无意义

提前谢谢:)

【问题讨论】:

  • cache = malloc(sizeof(*cache); 的语法错误。
  • 你只为cache->set[0].blocks分配内存。 cache->set[1].blocks 是一个垃圾指针。
  • 抱歉,由于某种原因,我的代码中的复制粘贴没有得到 cache_t 的 typedef。它已编辑。为什么我应该使用 sizeof(cache) 而不是 (*cache) 分配?在上一个问题中,我用同样的代码问过我被告知 sizeof(cache) 是错误的,应该是 sizeof(*cache)。介意解释吗?谢谢你:)
  • 我从来没有说过sizeof(cache)。 ???
  • 有人说 malloc(sizeof(chace)) 是错误的,我应该使用 malloc(sizeof(*cache)) 代替。所以两个人告诉我不同​​的事情,只是想知道什么是真正正确的?谢谢你:)

标签: c pointers memory dynamic-memory-allocation


【解决方案1】:

您没有为 set[0] 之外的“block_t”分配内存。

大致上,您应该按照以下方式做一些事情:

cache = malloc(sizeof *cache);
cache->set = malloc(num_sets * sizeof *cache->set);
for (i = 0; i < num_sets; i++) {
    cache->set[i].blocks = malloc(...);
}

【讨论】:

  • 非常感谢!事实证明,只是我对这个主题的了解太少了!非常感谢!
猜你喜欢
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2020-08-15
相关资源
最近更新 更多