首页 > 解决方案 > 自定义 malloc,分段错误

问题描述

我正在做一个自定义malloc。我做了一个非常简单的操作,但现在我正在尝试合并和拆分块,以提高对sbrk(). 当我尝试执行一个没有很多 malloc 的自定义程序时,它工作得很好。但是,一旦我尝试更多的 malloc 或例如ls一些成功分配后的命令,它就会在调用 split 函数时结束给出一个奇怪的分段错误(核心转储)。

任何帮助或提示将不胜感激。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include "struct.h"

static p_meta_data first_element = NULL;
static p_meta_data last_element  = NULL;

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

#define ALIGN8(x) (((((x)-1)>>3)<<3)+8)
#define MAGIC     0x87654321

void *malloc(size_t size_bytes);
p_meta_data search_available_space(size_t size_bytes);
p_meta_data request_space(size_t size_bytes);
p_meta_data merge(p_meta_data meta_data1, p_meta_data meta_data2);
void split(p_meta_data meta_data, size_t size_bytes);
void free(void *ptr);
void *calloc(size_t num_bytes, size_t num_blocs);
void *realloc(void *ptr, size_t size_bytes);

p_meta_data search_available_space(size_t size_bytes) {
    p_meta_data current = first_element; 
    while (current && !(current->available && current->size_bytes >= size_bytes)){
        fprintf(stderr, " %zu libre %d\n", current->size_bytes, current->available);
        current = current->next;
    }
    if (current == NULL) {
        fprintf(stderr, "null\n" );
    } else {
        fprintf(stderr, "%zu libre %d\n", current->size_bytes, current->available);
    }
    return current;
}

p_meta_data request_space(size_t size_bytes) {
    if (size_bytes < 122880) {
        size_bytes = 122880;
        fprintf(stderr, "request %zu\n", size_bytes);
    }
    p_meta_data meta_data;

    meta_data = (void *)sbrk(0);
    if (sbrk(SIZE_META_DATA + size_bytes) == (void *)-1)
        return (NULL);

    meta_data->size_bytes = size_bytes;
    meta_data->available = 0;
    meta_data->magic = MAGIC;
    meta_data->next = NULL;
    meta_data->previous = NULL;
    return meta_data;
}

p_meta_data merge(p_meta_data meta_data1, p_meta_data meta_data2) {
    if (!meta_data1 || !meta_data2) {
        return NULL;
    }

    meta_data1->size_bytes = meta_data1->size_bytes + SIZE_META_DATA + meta_data2->size_bytes;
    meta_data1->next = meta_data2->next;
    if (last_element == meta_data2) {
        fprintf(stderr, "gleich\n");
        last_element = meta_data1;
    }
    meta_data2 = NULL;

    return meta_data1;
}

void free(void *ptr) {
    p_meta_data meta_data;

    if (!ptr)
        return;

    pthread_mutex_lock(&mutex);

    meta_data = (p_meta_data)(ptr - SIZE_META_DATA);

    if (meta_data->magic != MAGIC) {
        fprintf(stderr, "ERROR free: value of magic not valid\n");
        exit(1);
    }

    meta_data->available = 1;
    fprintf(stderr, "Free at %x: %zu bytes\n", meta_data, meta_data->size_bytes);

    p_meta_data meta_data_prev, meta_data_next;
    meta_data_prev = meta_data->previous;
    meta_data_next = meta_data->next;

    if (meta_data_prev && meta_data_prev->available) {
        meta_data = merge(meta_data_prev, meta_data);
    }
    if (meta_data_next && meta_data_next->available) {
        meta_data = merge(meta_data, meta_data_next);
    }

    pthread_mutex_unlock(&mutex);
}

void split(p_meta_data meta_data, size_t size_bytes) {
    if (!meta_data) {
        fprintf(stderr, "no deberia entrar\n");
        return;
    }
    p_meta_data meta_data2;

    size_t offset = SIZE_META_DATA + size_bytes;

    meta_data2 = (p_meta_data)(meta_data + offset);

    fprintf(stderr, "size of metadata %d", meta_data->size_bytes - size_bytes - SIZE_META_DATA);

    meta_data2->size_bytes = meta_data->size_bytes - size_bytes - SIZE_META_DATA;
    meta_data2->available = 1;
    meta_data2->magic = MAGIC;
    meta_data2->previous = meta_data;
    meta_data2->next = meta_data->next;

    if (meta_data == last_element) {
        last_element = meta_data2;
    }

    meta_data->size_bytes = size_bytes;
    meta_data->next = meta_data2;

    return;
}

void *malloc(size_t size_bytes) {
    void *p, *ptr;
    p_meta_data meta_data;

    if (size_bytes <= 0) {
        return NULL;
    }

    size_bytes = ALIGN8(size_bytes);
    fprintf(stderr, "Malloc %zu bytes\n", size_bytes);

    // Bloquegem perque nomes hi pugui entrar un fil
    pthread_mutex_lock(&mutex);

    meta_data = search_available_space(size_bytes);

    if (meta_data) { // free block found
        fprintf(stderr, "FREE BLOCK FOUND---------------------------------------------------\n");
        meta_data->available = 0; //reservamos el bloque
    } else {     // no free block found
        meta_data = request_space(size_bytes); //pedimos más espacio del sistema
        if (!meta_data) //si meta_data es NULL (es decir, sbrk ha fallado)
            return (NULL);

        if (last_element) // we add the new block after the last element of the list
            last_element->next = meta_data;
        meta_data->previous = last_element;
        last_element = meta_data;

        if (first_element == NULL) // Is this the first element ?
            first_element = meta_data;
    }

    fprintf(stderr, "die differenz %zu\n", meta_data->size_bytes - size_bytes);
    if ((meta_data->size_bytes - size_bytes) > 12288) {
        split(meta_data, size_bytes);
        fprintf(stderr,"call split\n");
    }

    p = (void *)meta_data;

    // Desbloquegem aqui perque altres fils puguin entrar
    // a la funcio
    pthread_mutex_unlock(&mutex);

    // Retornem a l'usuari l'espai que podra fer servir.
    ptr = p + SIZE_META_DATA; //p es puntero al inicio de meta_data, y ptr es el puntero al inicio del bloque de datos en sí (justo después de los metadatos)
    return ptr;
}

void *calloc(size_t num_bytes, size_t num_blocs) {
    size_t mem_to_get = num_bytes * num_blocs;
    void *ptr = malloc(mem_to_get);
    if (ptr == NULL) {
        return ptr;
    } else {
        memset(ptr, 0, mem_to_get);
        return ptr;
    }
}

void *realloc(void *ptr, size_t size_bytes) {
    fprintf(stderr, "realloc\n");
    if (ptr == NULL) {
        return malloc(size_bytes);
    } else {
        p_meta_data inic_bloc = (p_meta_data )(ptr - SIZE_META_DATA);
        if (inic_bloc->size_bytes >= size_bytes) {
            return ptr;
        } else {
            void *new_p = malloc(size_bytes);
            memcpy(new_p, ptr, inic_bloc->size_bytes);
            inic_bloc->available = 1;
            return new_p;
        }
    }
}

其中 struct.h 是:

#include <stddef.h>
#include <unistd.h>

#define SIZE_META_DATA  sizeof(struct m_meta_data)
typedef struct m_meta_data *p_meta_data;

/* This structure has a size multiple of 8 */

struct m_meta_data {
    size_t  size_bytes;
    int     available;
    int     magic;
    p_meta_data next;
    p_meta_data previous;
};

标签: cmemorymemory-managementmalloc

解决方案


以下是有关您的代码的一些说明:

  • 将指针隐藏在 typedef 后面会让读者感到困惑。为什么不定义m_meta_data为 typedefstruct m_meta_datam_meta_data *在任何地方使用?
  • 你确定sbrk()定义正确吗?演员(void *)sbrk(0)表似乎另有说明。在 POSIX 系统sbrk()中声明。<unistd.h>
  • 中的BUGsplit()计算meta_data2 = (p_meta_data)(meta_data + offset);不正确。它应该是:

    meta_data2 = (p_meta_data)((unsigned char *)meta_data + offset);
    
  • 您应该定义strdup()并且strndup()因为 C 库中的定义可能不会调用您的 redefined malloc()

    char *strdup(const char *s) {
        size_t len = strlen(s);
        char *p = malloc(len + 1);
        if (p) {
            memcpy(p, s, len + 1);
        }
        return p;
    }
    
    char *strndup(const char *s, size_t n) {
        size_t len;
        char *p;
    
        for (len = 0; len < n && s[n]; len++)
            continue;
        if ((p = malloc(len + 1)) != NULL) {
            memcpy(p, s, len);
            p[len] = '\0';
        }
        return p;
    }
    
  • 分配的块malloc()应在 64 位英特尔系统上的 16 字节边界上对齐。事实上,该m_meta_data结构在 64 位系统上的大小为 32 字节,但在 32 位系统上为 20 字节。您应该m_meta_data针对 32 位系统调整结构。

  • 你应该检查溢出size_t mem_to_get = num_bytes * num_blocs;
  • 你不应该依赖void *算术,它是一个 gcc 扩展。改为这样写:

    p_meta_data inic_bloc = (p_meta_data)ptr - 1;
    
  • 在 中realloc(),当扩展块的大小时,您只需使原始块可用,但不会像在 中那样将其与相邻块合并free()。您可能只是调用free(ptr),特别是因为inic_bloc->available = 1;在没有获得锁的情况下进行修改似乎有风险。

  • 您应该检查meta_data->available并检测无效呼叫free()realloc()防止竞技场损坏。

  • malloc(),您忘记释放锁以防分配失败。

  • 在设置锁时调用fprintf是有风险的:如果fprintf调用malloc,你会遇到死锁。您可能会认为 print tostderr不会调用malloc(),因为stderr没有缓冲,但您正在冒险。

  • 使用 分配新块时sbrk(),应sbrk(0)在分配后使用以确定可用的实际大小,因为它可能已四舍五入为PAGE_SIZE.

  • 如果 . 你应该拆分块(meta_data->size_bytes - size_bytes) > SIZE_META_DATA。目前的测试太松散了。


推荐阅读