访问数组分段错误中的数据
Accessing data in array segmentation fault
我在我的程序中遇到了一个分段错误,我很确定这是一个愚蠢的错误!当我尝试访问我的结构数组中的数据时,出现分段错误。
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
看来是标签变量的问题?对我来说毫无意义
提前致谢:)
您没有为 "block_t" 超出集合 [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(...);
}
我在我的程序中遇到了一个分段错误,我很确定这是一个愚蠢的错误!当我尝试访问我的结构数组中的数据时,出现分段错误。
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
看来是标签变量的问题?对我来说毫无意义
提前致谢:)
您没有为 "block_t" 超出集合 [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(...);
}