【问题标题】:C Programming: Segmentation fault at struct ptr. Memory alloc issueC 编程:结构 ptr 处的分段错误。内存分配问题
【发布时间】:2018-12-27 23:00:20
【问题描述】:

我在运行时遇到段错误:

我正在尝试在 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_) );
       // }
    }

【问题讨论】:

  • 欢迎来到 SO。您是否使用调试器来跟踪分段错误?你检查过涉及的变量吗? i 中存储了哪个值?
  • 在你的for循环中:for (i=0; i&lt;cache-&gt;numSets; i++) {cache-&gt;numSets的值没有设置。
  • 您在malloc 中使用numSets,但在循环条件子句中使用cache-&gt;numSets。后者可能没有正确设置(例如)在malloc之后,做:cache-&gt;numSets = numSets;
  • 你的代码可能是一个例子,为什么你不应该在 typedef 中隐藏指针类型
  • 如果有人无法使用您当前发布的“sn-ps”复制错误,那么您可能需要考虑通过编辑您的问题来更新您的代码。这很响亮,有助于其他人更快地发现错误。问题从“问题分类”发送到“需要编辑”。尽情享受吧 ;-)

标签: c caching segmentation-fault


【解决方案1】:

Set 是指向struct Set_ 的指针,所以你的 malloc

cache->set = (Set *) malloc( numSets * sizeof( Set ) );

保留指针,而不是struct Set_-objects。 重写为

cache->set = (Set *) malloc( numSets * sizeof( struct Set_ ) );

至少应该有助于解决这个问题。

【讨论】:

  • 不幸的是,cache-&gt;set 的类型是 Set*,而不是 struct Set_
  • 谢谢。让我试试这个。
  • typedef struct CacheMemory* Cache; typedef struct Set_ Set; // changed from Set_ *Set; typedef struct Block_ Block; // changed from Block_ Block; 并在 malloc 中将其更改为计算 struct Set_ ( cache-&gt;set = (Set *) malloc( numSets * sizeof( Set_ ) ); ) 的大小,这似乎解决了问题。在另一个区域出现段错误。将很快更新感谢您的所有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-06-14
  • 2021-08-06
  • 1970-01-01
  • 2018-01-29
  • 2017-07-26
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多