【发布时间】: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