我在运行时遇到段错误:
我正在尝试用 C 语言构建这个缓存模型。
所以,代码编译得很好,但我在运行时遇到了段错误。 我追踪到这一行:
cache->set[i]->block = (Block *) malloc(cache->numSets * sizeof( Block ) );
我尝试将 Block 作为 Set 结构内部的数组。但这会带来其他问题,事实上也会带来相同的段错误。
typedef struct CacheMemory* Cache;
typedef struct Set_* Set;
typedef struct Block_* Block;
struct Block_ {
int valid;
int tag; // int *tag;
int dirty;
};
struct Set_ {
int numBlocks;
Block *block;
};
struct CacheMemory {
<snip>
Set *set;
};
Cache cache;
cache = (Cache) malloc(sizeof ( struct CacheMemory ) );
cache->set = (Set *) malloc( numSets * sizeof( Set ) );
for (i=0; i<cache->numSets; i++) {
//for (j = 0; j < cache->blockSize; j=j+1) {
// Note: I get segfault at line below during runtime
cache->set[i]->block = (Block *) malloc( cache->numSets *sizeof( Block ) );
//cache->set[i]->block[j] = (Block_) malloc (sizeof(Block_) );
// }
}
最佳答案
Set
是一个指向 struct Set_
的指针,所以你的 malloc
cache->set = (Set *) malloc( numSets * sizeof( Set ) );
保留指针,而不是struct Set_
对象。
将其重写为
cache->set = (Set *) malloc( numSets * sizeof( struct Set_ ) );
至少应该有助于解决这个问题。
关于C 编程 : Segmentation fault at struct ptr. 内存分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53951786/