Malloc和Void指针

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

static void *malloc(int size) { void *p; if (size = free_mem_end_ptr) error("Out of memory"); malloc_count++; return p; } 

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

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

它如何指向任何类似的数据类型? 我只是无法理解void指针或其位置。

注意:malloc_ptr是unsigned long

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

这是malloc实现 ,因此允许执行在常规程序中不合法的事情。 具体来说,它正在利用从unsigned longvoid *的实现定义转换。 程序初始化将malloc_ptr为大块未分配内存的数字地址 。 然后,当您请求分配时, malloc会从malloc_ptr的当前值中指出一个指针,并将malloc_ptr增加您要求的字节数。 这样,下次调用malloc时它将返回一个新指针。

这是关于malloc最简单的可能实现。 最值得注意的是,它似乎永远不会重复使用释放的内存。

Malloc正在为一块完全非结构化的平坦内存返回一个指针。 (void *)指针意味着它不知道它指向什么(没有结构),只是它指向一些大小的内存。

在调用malloc之外,您可以告诉程序该指针有一些结构。 即,如果你有一个结构some_struct你可以说: struct some_struct *pStruct = (struct some_struct *) malloc(sizeof(struct some_struct))

看看malloc如何只知道它要分配的大小,但实际上并不知道它的结构? 您对malloc的调用没有传递有关结构的信息,只传递了要分配的内存大小。

这是C的通用方式:malloc返回一定数量的内存,你的工作就是把它投射到你需要的结构化内存中。

  p = (void *)malloc_ptr; `malloc` returns a void pointer, which indicates that it is a pointer to a region of unknown data type. The use of casting is only required in C++ due to the strong type system, whereas this is not the case in C. The lack of a specific pointer type returned from `malloc` is `type-unsafe` behaviour according to some programmers: malloc allocates based on byte count but not on type. malloc_ptr += size; `C` implicitly casts from and to `void*`, so the cast will be done automatically. In `C++` only conversion to void* would be done implicitly, for the other direction an explicit cast is required. 

Wiki关于类型转换的解释,

 `malloc` function returns an untyped pointer type `void *`, which the calling code must cast to the appropriate pointer type. Older C specifications required an explicit cast to do so, therefore the code `(struct foo *) malloc(sizeof(struct foo))` became the accepted practice. However, this practice is discouraged in ANSI C as it can mask a failure to include the header file in which `malloc` is defined, resulting in downstream errors on machines where the int and pointer types are of different sizes, such as the now-ubiquitous x86_64 architecture. A conflict arises in code that is required to compile as C++, since the cast is necessary in that language. 

如你所见这两条线,

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

这里你有malloc_ptr类型为unsigned long,所以我们将这个变量类型转换为void类型,然后将它存储在p中。 以类似的方式,第二个表示malloc_ptr = malloc_ptr + size;

这两个代码都是为了开发人员的舒适性,因为p是void指针类型所以在应用程序中使用malloc然后你不知道哪个类型的内存块必须通过函数返回,所以这个函数总是返回这个通用的void指针所以我们可以根据要求在我们的应用程序中再次进行类型转换。

如果输入大小为负数,则在第二个代码中相同,那么此条件会发生什么

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