Malloc和空指针 [英] Malloc and Void Pointers

查看:280
本文介绍了Malloc和空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究此malloc函数,可以使用一些帮助:

I'm studying this malloc function and I could use some help:

static void *malloc(int size)
  {
        void *p;

        if (size < 0)
                 error("Malloc error");
        if (!malloc_ptr)
                 malloc_ptr = free_mem_ptr;

        malloc_ptr = (malloc_ptr + 3) & ~3;     /* Align */

        p = (void *)malloc_ptr;
        malloc_ptr += size;

        if (free_mem_end_ptr && malloc_ptr >= free_mem_end_ptr)
                 error("Out of memory");

        malloc_count++;
        return p;
 }

我知道,如果有足够的内存,则malloc函数可以为任何类型分配内存空间,但是我不理解的行是:

I know that the malloc func allocates memory space for any type, if there is enough memory, but the lines i don't understand are:

p = (void *)malloc_ptr;
malloc_ptr += size;

它如何指向这样的任何数据类型?我只是不明白那个空指针或它的位置.

How can it point to any data type like that? I just can't understand that void pointer or its location.

注意:malloc_ptr是无符号长

NOTE: malloc_ptr is an unsigned long

推荐答案

返回空指针的原因是因为它不知道您要在malloc调用中分配什么空间.它所知道的只是您请求的空间量.由您或您的编译器决定什么将填充内存.空指针的位置通常以链接列表的形式实现,以保持完整性并知道哪些内存值可用,这在free函数中令人惊讶地保持了跟踪.

The reason it returns a void pointer is because it has no idea what you are allocating space for in the malloc call. All it knows is the amount of space you requested. It is up to you or your compiler to decide what will fill the memory. The void pointer's location is typically implemented as a linked list to maintain integrity and know what values of memory are free which is surprisingly kept track of in the free function.

这篇关于Malloc和空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆