关于虚拟内存的分配和管理的一些API
大概了解一下Unix系统中内存分配接口(memory allocation interfaces in Unix systems),这里先只是:
- 介绍2种内存管理的库调用
- 详细介绍堆上内存手动分配和释放函数(malloc/free)
问题的关键在于:
怎样分配和管理内存
1. 内存种类(Types of Memory)
In running a C program, there are two types of memory that are allocated.
- stack/automatic memory
The first is called stack memory, and allocations and deallocations
of it are managed implicitly by the compiler for you, the programmer; for
this reason it is sometimes called automatic memory.
Ex:
void func() {
int x; // declares an integer on the stack
...
}
The compiler does the rest, making sure to make space on the stack
when you call into func(). When you return from the function, the compiler deallocates thememory for you; thus, if you want some information to live beyond the call invocation, you had better not leave that information on the stack.
但是,随着调用func()函数结束,分配的动态分配的内存自动释放。所以,这里有个需求:
自己分配/释放内存,所以,就有了heap
- heap memory
heap memory, where all allocations and deallocations are explicitly handled by you.
Ex:
void func() {
int *x = (int *) malloc(sizeof(int));
...
}
both stack and heap allocation occur on this line:
First, the compiler knows to make room for a pointer to an integer when it sees your declaration of said pointer (int *x);
subsequently, when the program calls malloc(), it requests space for an integer on the heap;
the routine returns the address of such an integer (upon success, or NULL on failure), which is then stored on the stack for use by the program.
Because of its explicit nature, and because of its more varied usage,
heap memory presents more challenges to both users and systems. Thus,
it is the focus of the remainder of our discussion.
2. The malloc() Call
The malloc() call is quite simple: you pass it a size asking for some
room on the heap, and it either succeeds and gives you back a pointer to
the newly-allocated space, or fails and returns NULL.
对于NULL:
NULL in C isn’t really anything special at all, just a macro for the value zero.
Ex:
man malloc
#include <stdlib.h>
...
void *malloc(size_t size);
From this information, you can see that all you need to do is include
the header file stdlib.h to use malloc. In fact, you don’t really need to
even do this, as the C library, which all C programs link with by default, has the code for malloc() inside of it; adding the header just lets the compiler checkwhether you are calling malloc() correctly (e.g., passing the right number of arguments to it, of the right type).The single parameter malloc() takes is of type size t which simply
describes how many bytes you need. However, most programmers
do not type in a number here directly (such as 10); indeed, it would be
considered poor form to do so. Instead, various routines and macros are
utilized.
For example, to allocate space for a