Of C in the malloc and free

2010-05-26  来源:本站原创  分类:CPP  人气:224 

In the C language, learning, memory management is particularly important to grasp some knowledge! C before the malloc () and free () the two functions are poorly understood, only know about how to use - is the malloc and free on all OK. Of course, now the two functions are not necessarily more experience, but for the third part of the contents of this article with turning-point understanding of Dao Shi, so

Wrote this article as a summary of knowledge. The reason why this article has a name "of" words, that is, mean it! Hope to have a little help!

If you do not share too much if (for example the operating system virtual memory and physical memory given to how the knowledge of how to manage the class, etc.), I feel this article should be a more comprehensive comment about the malloc () and free () . This article implemented progressively (not necessarily the depth) section describes three main elements.

So much nonsense, immediate access to the following topics ================""""""""""""""""""""""""" """""""""""

1, malloc () and free () the basic concept and basic usage:

1, the function prototype and description:

void * malloc (long NumBytes): This function allocates NumBytes bytes, and returns a pointer to point to this memory. If the allocation fails, it returns a null pointer (NULL).

On the distribution of failure, there should be multiple, for example, is a lack of space.

void free (void * FirstByte): before the function is to allocate space with malloc return the program or operating system, which is released this memory, it re-free.

2, the function of usage:

In fact, these two functions together not that difficult to use, that is, malloc () after that cast off with enough of it to give it to free (), and give a simple example:

Code:
/ / Code ...
char * Ptr = NULL;
Ptr = (char *) malloc (100 * sizeof (char));
if (NULL == Ptr)
(
exit (1);
)
gets (Ptr);

/ / Code ...
free (Ptr);
Ptr = NULL;
/ / Code ...

Is it! Of course, the specific situation and specific solutions to specific analysis. For example, you define a pointer, in a function to apply a piece of memory and then through a function Fanhui passed to this pointer, then perhaps the release of this piece of work is Neicunzhexiang should be left to other functions of the.

3, on the function uses a number of areas requiring attention:

A, application memory space, you must check whether the distribution of success.

B, when no need to use the application memory, the recall release; release should point to this piece of memory pointer to NULL, to prevent the process behind the careless use of it.

C, these two functions should be matched. If the application does not release that memory leak; release if that is no reason to do nothing. Released only once, twice, and if more than two will be released

Error (null pointer exception to the release, the release of a null pointer is actually equal to Shaye Mo, so the number of times the release of the release of a null pointer, no problems).

D, although the malloc () function is of type (void *), any type can be converted into a pointer (void *), but the best type of conversion in front of the mandatory, because it can avoid a

More compiler checking.

Well! Probably the most basic thing to say! Now the second part:

Second, malloc () in the end come from where memory space:

1, malloc () in the end from where you got the memory space? The answer is obtained from the heap inside the space. That function returns the pointer is pointing to a heap inside the memory. Operating system has a record of free memory address list. When the operating system before the application process, will traverse the list, then find the first space is greater than the node for the heap space, then the node list from a free node is removed and the knot point of space allocated to the program. Is it!

Here, have another into a small topic, I believe we all know what topics. What is the heap? Speaking of balls, could not help but say the stack! What is stack? The following section is devoted to another to open a small and simple to say about this aside:

2, What is the heap: heap is a shared space, sub-global heap and local stack. The global heap is not allocated all the space, the local heap is allocated user space. Heap in the process of initializing the operating system on time allocation, the operation process can be additional to the system heap, but I remember running out to return the operating system, or else a memory leak.

What is the stack: stack is a unique thread, save the running state and local automatic variables. Stack in the beginning of the initialization thread, each thread's stack, independent of each other. Each function has its own stack, the stack is used to pass parameters between functions. When the operating system will automatically switch thread switch stack, that is, switch SS / ESP register. Stack space in the high-level language which does not require explicit allocation and release.

The concept described above is the standard description, but I delete individual statement is, do not know because it does not become the standard of the ^ _ ^.

On the face of the concept through the description, you can know:

Stack is automatically allocated by the compiler release, storage function parameters, local variables, etc.. Mode of operation similar to the data structure in the stack.

Heap allocation of general release by the programmer, if released, end of the process may recover from the OS. Note here that it is possible, not necessarily. So I would emphasize again, remember to release!

Note that with the heap data structure is different from the methods of distribution Daoshi similar to the list. (Which I mentioned a little above)

So, for example, if you defined above in the function of a pointer variable, and then apply this function in a piece of memory for a pointer point to it. In fact, the pointer's address is in the stack, but the content it points to is in the heap above! It is important to note! So think again, applied in a function in the space, for example, the following functions:

Code:
/ / Code ...
void Function (void)
(
char * p = (char *) malloc (100 * sizeof (char));
)

On this example, do not think that the function returns, the function where the stack pointer has been destroyed along with the destruction, for the same memory also followed the destruction! This is absolutely wrong! Because the application of memory in the heap, and the function stack where the heap is destroyed with no Sha relationship. Therefore, I reiterate: I remember the release!

3, free () in the end what the release of

The problem is rather simple, but I want to echo the title of second most it! Haha! free () releases the pointer to the memory! Attention! The release of the memory, not a pointer! This is very, very important! Pointer is a variable, only the end of the process only to be destroyed. Free memory space, the original pointer to point to this piece of space still exists! Only now, the contents of the garbage pointer is undefined, so is garbage. Therefore, I have said before, after releasing the memory pointer to NULL, the pointer in the back to prevent it being accidentally Solution references. Ah this is very important!

Well! This "digression" finally end. As simple as that, in a rough idea about him! Here enters the third part:

3, malloc () and free () mechanism:

This part I have a new understanding of today! And is turning-point understanding! Therefore, this part may be a little more understanding of the error! Please help wrong with that!

In fact, a closer look free () function prototype, may also find that it seems magical, free () function is very simple, only one parameter, as long as the transfer point for space pointer

To free () the parameters can be completed in the release of work! Here we tracing to malloc () the application problem. When in fact for the memory than for large. Because of the excess space is used to record information on the management of this memory. A look at the "UNIX high-level programming environment," in Chapter VII of the passage:

Most of the storage space allocated to achieve the required ratio to be slightly larger, additional space for records management information - the length of the block distribution, a distribution point to the next block pointer and so on. This means that if the written end of an allocated area will be rewritten after the piece of management information. This type of error is catastrophic, but because of this error will not soon be exposed, it also difficult to find. Pointer will point to the block allocation may also be rewritten backward movement of the block management information.

The above passage has given us some information on the. malloc () for the space actually I think it is two different kinds of sub-space. One is used to record management information space, another one is available space. And used to record management information is actually a structure. In the C language, with structure to record information with a different object is

A matter of course! Look at the structure following prototype:

Code:
struct mem_control_block (
int is_available; / / is a marker?
int size; / / this is the actual size of the space
);

For size, this is the actual space. Here in fact, I have a question, is_available it is a mark? I saw free () after the source code for this variable feel a bit puzzled (source code analysis below). Also please point out here!

Thus, free () is the basis of this structure information to release malloc () for the space! The structure of two members of the size of the operating system I think things should be. But here there is a problem, malloc () returns a pointer for the space should be pointing to the second space, that is, free space! Otherwise, if the point management information space, then write the type of content and structure may be inconsistent, or will management information blocked, it can not release the memory space, so an error! (Feel where he is being sarcastic)

Well! Look at the following free () the source code, I have analyzed, that the than malloc () source code is much simpler sounds easy. Just have a question, pointed out below!

Code:
/ / Code ...

void free (void * ptr)
(
struct mem_control_block * free;
free = ptr - sizeof (struct mem_control_block);
free-> is_available = 1;
return;
)

Look at the function, the second sentence, phrase is very important and critical. Sentence is actually a pointer to point to free space to go back, it points to the piece of management information space, because there is less value on the size of a structure! The latter a free-> is_available = 1; I am a bit puzzled! My idea is: there should be only a marker is_available it! Because from this point of view the name of the variable, is_available translates to "can be used." Do not say I land! I think the variable name to reflect the role of a variable, especially strict code. This is the source code, so I think that is absolutely rigorous! ! The value of this variable is 1, that can be used in space! Here I just thought, if it is other value to 0 or do not know what will happen? ! But one thing I am sure that will not release it smoothly! Because this is a tag!

Of course, there may still be some doubt, why this can be released? ? I just have this question. Then I thought, what the operating system release, then free () the source code view, nothing in the release, right? But it really is to determine the management information of the contents of that piece of memory. Thus, free () is only recorded some information, then tell the operating system release that piece of memory can go, how to tell the operating system specific, I do not know, but I think this is beyond the scope of this article I had.

Well, I have a misunderstanding before, is that piece of memory pointer points to move the piece of memory no matter which position can be released that piece of memory! But this is wrong! Is not part of the release of the release! First of all, should understand this point. Moreover, from free () the source code to see, ptr can point to the first address space available, or, after subtracting the size structure of management information must not point to the first address space. Therefore, to ensure that the pointer to the first address space available! Do not believe it? I can write a program and then move the pointer to point to available space, see program will be collapsing!

相关文章
  • Article 3: as far as possible new and delete replace malloc and free 2010-04-19

    1, malloc and free to bring the issue is simple: They constructor and destructor know nothing about. string * p1 = static_cast <string*> (malloc (10 * sizeof (string))); Note: 10 points enough for the string object's memory space, but the object is

  • Write your own malloc 2010-04-19

    1, if a program a lot of calls malloc, the program will consume a lot of time in a call to the malloc function. 2, write your own malloc. Given a template code: #define NODESIZE 8 #define NODEGROUP 100 int nodeleft=0; char* freenode; void* myMalloc(i

  • FreeBSD kernel malloc 2010-04-23

    FreeBSD kernal malloc is achieved through the zone allocaotor. The basic idea is to create some of the smaller memory zones, for a small memory allocation; in the allocation of more memory, use uma_large_malloc. kmeminit some initialization actions,

  • Heap and the stack C, malloc and free 2010-05-04

    Taken from: http://www.bccn.net/Article/kfyy/cyy/jszl/200608/4238.html The original posts and discussion: http://bbs.bccn.net/thread-82212-1-1.html In the C language, learning, memory management is particularly important to grasp some knowledge! C be

  • Of C in the malloc and free 2010-05-26

    In the C language, learning, memory management is particularly important to grasp some knowledge! C before the malloc () and free () the two functions are poorly understood, only know about how to use - is the malloc and free on all OK. Of course, no

  • C language memory allocation: malloc () function and alloc () function 2010-07-19

    This article describes the C language, malloc () function and alloc () function. C language with the memory allocation method (1) from the static storage area field distribution. Memory when the program has compiled a good distribution of this piece

  • C language: malloc () function and alloc () function 2010-07-24

    C language with the memory allocation method (1) allocation from the static storage area. Memory when the program has compiled a good distribution, this memory during the entire operation in the program are present. For example, global variables, sta

  • On the malloc and free C 2010-10-16

    In the C language, learning, memory management, this part of the knowledge is particularly important to master! C before the malloc () and free () the two functions are poorly understood, probably the only know how to use - that malloc and free to al

  • With the malloc / free why new / delete 2010-12-21

    With the malloc / free why new / delete? malloc and free are C + + / C language standard library functions, new / delete is a C + + operator. They can be used to apply dynamic memory and release memory. For non-internal data type of object, the light

  • malloc and free are C + + / C language standard library functions, new / delete is a C + + operator. They can be used to apply for the release of dynamic memory and memory 2010-12-21

    malloc and free are C + + / C language standard library functions, new / delete is a C + + operator. They can be used to apply for the release of dynamic memory and memory for non-internal data type of object, the light with maloc / free can not meet

  • c + + in the meaning and usage of malloc 2010-12-21

    A .malloc() And free() The basic concept and basic usage : 1. Function prototypes and descriptions : void *malloc(long NumBytes): The function allocates NumBytes bytes , And returns a pointer to a pointer to this memory. If the allocation fails , A n

  • Summary of malloc usage 2010-12-29

    1. Standard 3 steps: malloc + free + pointers to empty 2. Programming Example / * date: 20100824 description: malloc of using the specifications in parameters: number of bytes in the application heap memory, attention int, short, float needs its own

  • C + + memory allocation Cheats-new, malloc, GlobalAlloc Detailed 2011-05-04

    C + + memory allocation Cheats-new, malloc, GlobalAlloc Detailed _______ Just for memory allocation and can not sleep because of the programmer One. About Memory 1, memory allocation Memory allocation in three ways: (1) allocation from the static sto

  • 基于malloc与free函数的实现代码及分析 2013-10-11

    本篇文章介绍了malloc与free函数的实现代码及分析.需要的朋友参考下 用于内存管理的malloc与free这对函数,对于使用C语言的程序员应该很熟悉.前段时间听说有的IT公司以"实现一个简单功能的malloc"作为面试题,正好最近在复习K&R,上面有所介绍,因此花了些时间仔细研究了一下.毕竟把题目做出来是次要的,了解实现思想.提升技术才是主要的.本文主要是对malloc与free实现思路的介绍,蓝色部分文字是在个人思考中觉得比较核心的东西:另外对于代码的说明,有一些K&a

  • c语言中malloc.realloc与calloc 的区别以及联系 2014-02-02

    以下是对c语言中的malloc函数,realloc函数与calloc函数的区别以及它们之间的联系进行了介绍,需要的朋友可以过来参考下 ANSI C说明了三个用于存储空间动态分配的函数(1) malloc分配指定字节数的存储区.此存储区中的初始值不确定 (2) calloc为指定长度的对象,分配能容纳其指定个数的存储空间.该空间中的每一位(bit)都初始化为0 (3) realloc 更改以前分配区的长度(增加或减少).当增加长度时,可能需将以前分配区的内容移到另一个足够大的区域,而新增区域内的初

  • 如何实现一个malloc 2014-03-08

    任何一个用过或学过C的人对malloc都不会陌生.大家都知道malloc可以分配一段连续的内存空间,并且在不再使用时可以通过free释放掉.但是,许多程序员对malloc背后的事情并不熟悉,许多人甚至把malloc当做操作系统所提供的系统调用或C的关键字.实际上,malloc只是C的标准库中提供的一个普通函数,而且实现malloc的基本思想并不复杂,任何一个对C和操作系统有些许了解的程序员都可以很容易理解. 这篇文章通过实现一个简单的malloc来描述malloc背后的机制.当然与现有C的标准库

  • C++中new与delete.malloc与free应用分析 2014-06-20

    这篇文章主要介绍了C++中new与delete.malloc与free应用分析,很重要的概念,需要的朋友可以参考下 一般来说,在C/C++的面试时,对于new/delete和malloc/free这两对的使用和区别经常被考查到,如果这种基础的问题都答不上来,估计很难过面试了.本文即是对new/delete和malloc/free这两对的使用和区别较为简单的分析一下,供大家参考. 一.new和delete new和delete是C++的运算符,用于动态分配内存和释放内存. 1.new表达式 标准库

  • TCMalloc:线程缓存的Malloc 2014-07-24

    动机 TCMalloc要比glibc 2.3的malloc(可以从一个叫作ptmalloc2的独立库获得)和其他我测试过的malloc都快.ptmalloc在一台2.8GHz的P4机器上(对于小对象)执行一次malloc及free大约需要300纳秒.而TCMalloc的版本同样的操作大约只需要50纳秒.malloc版本的速度是至关重要的,因为如果malloc不够快,应用程序的作者就很有可能在malloc之上写一个自己的自由列表.这就可能导致额外的代码复杂度,以及更多的内存占用??除非作者本身非常

  • new和malloc的区别深入解析 2014-09-17

    以下是分别是对new和malloc的区别进行了详细的分析及介绍,需要的朋友可以过来参考下 1. malloc()函数1.1 malloc的全称是memory allocation,中文叫动态内存分配. 原型:extern void *malloc(unsigned int num_bytes); 说明:分配长度为num_bytes字节的内存块.如果分配成功则返回指向被分配内存的指针,分配失败返回空指针NULL.当内存不再使用时,应使用free()函数将内存块释放. 1.2 void *mallo

  • C语言中多维数组的内存分配和释放(malloc与free)的方法 2015-01-17

    写代码的时候会碰到多维数组的内存分配和释放问题,在分配和释放过程中很容易出现错误.下面贴上一些示例代码,以供参考. 如果要给二维数组(m*n)分配空间,代码可以写成下面: char **a, i; // 先分配m个指针单元,注意是指针单元 // 所以每个单元的大小是sizeof(char *) a = (char **) malloc(m * sizeof(char * )); // 再分配n个字符单元, // 上面的m个指针单元指向这n个字符单元首地址 for(i = 0; i < m; i+