C 编程 : Segmentation fault at struct ptr. 内存分配问题

标签 c caching segmentation-fault

我在运行时遇到段错误:

我正在尝试用 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/

相关文章:

c - 如何使用 glShaderStorageBinding 绑定(bind)着色器缓冲区 block ?

android - 如何最小化Android应用程序缓存大小

caching - 由同一应用程序的多个实例共享 redis 实例

c - 为什么这个 C 程序会在这个位置出现段错误?

python - PySide 关机时出现段错误

将枚举定义转换为无符号整数

c - 请帮助真正陷入结构困境

c - 来自 C 中输入文件的 fgets 的段错误

c - 我如何配置 Vim 以在 Windows 上使用 Borland 的编译器编译 C 代码?

iphone - iPhone 的缓存/离线 map ?