在C中创建自己的malloc函数

gho*_*der 2 c malloc

我需要你的帮助.我对C有一个平均的知识,这就是问题所在.我将使用一些基准来测试新处理器上的一些计算机体系结构(分支未命中,缓存未命中).关于它的事情是基准测试在C中,但我不能包含任何库调用.例如,我不能使用malloc因为我收到了错误

"undefined reference to malloc" 
Run Code Online (Sandbox Code Playgroud)

即使我已经包括了图书馆.所以我必须编写自己的malloc.我不希望它超级高效 - 只需要做基础知识.正如我在想的那样,我必须在内存中有一个地址,并且每当malloc发生时,我都会返回一个指向该地址的指针并按该大小递增计数器.Malloc在我的程序中发生了两次,所以我甚至不需要大内存.

你能帮帮我吗?我设计了一个Verilog并且在C中没有那么多经验.

我见过以前的答案但对我来说似乎都太复杂了.此外,我无法访问KR书.

干杯!

编辑:也许这可以帮助你更多:我不是使用gcc而是使用sde-gcc编译器.它有什么不同吗?也许这就是为什么我得到一个未定义的malloc引用?

EDIT2:我正在测试MIPS架构:

我包括:

#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

而错误是:

undefined reference to malloc
relocation truncated to fit: R_MIPS_26 against malloc
Run Code Online (Sandbox Code Playgroud)

和编译器命令id:

test.o: test.c cap.h
sde-gcc -c -o test.s test.c -EB -march=mips64 -mabi=64 -G -O -ggdb -O2 -S
    sde-as -o test.o test.s EB -march=mips64 -mabi=64 -G -O -ggdb
    as_objects:=test.o init.o
Run Code Online (Sandbox Code Playgroud)

编辑3:好的,我使用上面的实现,它运行没有任何问题.问题是,在进行嵌入式编程时,您只需定义所使用的所有内容,因此我定义了自己的malloc.sde-gcc无法识别malloc函数.

nos*_*nos 19

这是一个非常简单的方法,可能会让你通过你的2个mallocs:

static unsigned char our_memory[1024 * 1024]; //reserve 1 MB for malloc
static size_t next_index = 0;

void *malloc(size_t sz)
{
    void *mem;

    if(sizeof our_memory - next_index < sz)
        return NULL;

    mem = &our_memory[next_index];
    next_index += sz;
    return mem;
}

void free(void *mem)
{
   //we cheat, and don't free anything.
}
Run Code Online (Sandbox Code Playgroud)

如果需要,您可能需要对齐您回忆的内存片,例如,您总是返回内存地址,该地址位于4,8,16或您需要的任意数量的地址上.

  • -1 因为由于对齐问题,这将不起作用。Malloc 必须考虑对齐要求,这就是为什么标准 malloc 总是返回与最严格的对齐要求对齐的内存。您的内存缓冲区和实现都不会这样做。 (2认同)
  • 我认为你的意思是`if(sizeof our_memory - next_index <sz)`.(如果我们要分配的内存量是_less_而不是我们要求的内存然后返回`NULL`.) (2认同)
  • @ghostrider根据编译器的文档,malloc应该可以正常工作.您可能有一些安装/配置问题.该平台也是对齐敏感的,所以这个代码definitelly将无法正常工作. (2认同)

Cha*_*anK 5

尝试上面给出的线程安全 nos 答案,我指的是他的代码,并进行了一些更改,如下所示:

static unsigned char our_memory[1024 * 1024]; //reserve 1 MB for malloc
static size_t next_index = 0;

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *malloc(size_t sz)
{
    void *mem;
    pthread_mutex_lock(&lock);
    if(sizeof our_memory - next_index < sz){
        pthread_mutex_unlock(&lock);
        return NULL;
    }

    mem = &our_memory[next_index];
    next_index += sz;
    pthread_mutex_unlock(&lock);
    return mem;
}

void free(void *mem)
{
   //we cheat, and don't free anything.
} 
Run Code Online (Sandbox Code Playgroud)