【问题标题】:OS Cache Implementation: Segmentation Fault when using malloc操作系统缓存实现:使用 malloc 时出现分段错误
【发布时间】:2022-01-13 22:54:56
【问题描述】:

我正在编写一个代码来处理操作系统发出的缓存请求,当我尝试为我的缓存分配内存时,我遇到了分段错误,我不知道为什么。对此的任何帮助将不胜感激。

struct item {
char *key; 
struct file_data *value; 
int ref_count;
int size; 
struct item *next; 
}; 

struct wc {
    int capacity; 
    struct item **table; 
};

struct cache {
    struct wc *cache_table; 
    struct queue *cache_queue;
    int size; 
};

    struct server {
        int nr_threads;
        int max_requests;
        int max_cache_size;
        int exiting;
        /* add any other parameters you need */
        pthread_t *thread_array;
    int *buffer; 
    int buffer_in; 
    int buffer_out; 
    struct cache *cache; 
};


/* creating & initializing a hash table */ 
struct cache *cache_init(void)
{
    struct cache *initialized_cache = (struct cache *)malloc(sizeof(struct cache)); 

/* seg faulting in the following line*/
    if( (initialized_cache->cache_table->table = malloc(MAX_CACHE_TABLE_SIZE * sizeof(struct item**))) == NULL){
        return NULL; 
    }

【问题讨论】:

标签: c segmentation-fault malloc


【解决方案1】:

这一行:

struct cache *initialized_cache = (struct cache *)malloc(sizeof(struct cache)); 

创建一个用未初始化字节填充的堆对象。

这一行:

if( (initialized_cache->cache_table->table = malloc...

从该对象中获取一个 unitialized 指针,并尝试取消引用它。

当然它会崩溃1

您需要先将initialized_cache->cache_table 指向某处,然后才能取消引用它。


1 不能保证它会崩溃,它可能会写入一些随机内存,从而破坏您在其他地方的状态,并使错误更难找到。

你是幸运它崩溃了。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2017-06-06
    • 1970-01-01
    • 2018-09-24
    • 2021-03-18
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    相关资源
    最近更新 更多