Pointers on C——11 Dynamic Memory Allocation.6

来源:互联网 发布:sql注入 跑管理员 编辑:程序博客网 时间:2024/06/03 04:28

11.7 Summary


When an array is declared, its size must be known at compile time. Dynamic allocation allows a program to create space for an array whose size isnʹt known until runtime.

当数组被声明时,必须在编译时知道它的长度。动态内存分配允许程序为一个长度在运行时才知道的数组分配内存空间。


The malloc and calloc functions both allocate memory and return a pointer to it. The argument to malloc is the number of bytes of memory needed. In contrast,calloc requires the number of elements you want and the size of each element. calloc initializes the memory to zero before returning, whereas malloc leaves the memory uninitialized. The realloc function is called to change the size of an existing block of dynamically allocated memory. Increases in size may be accomplished by copying the data from the existing block to a new, larger block. When a dynamically allocated block is no longer needed, free is called to return it to the pool of available memory.Memory must not be accessed after it has been freed.

malloc 和calloc 函数都用于动态分配一块内存,并返回一个指向该块内存的指针。malloc 的参数就是需要分配的内存的字节数。和它不同的是, calloc 的参数是你需要分配的元素个数和每个元素的长度。calloc 函数在返回前把内存初始化为零,而malloc 函数返回时内存并未以任何方式进行初始化。调用realloc 函数可以改变一块已经动态分配的内存的大小。增加内存块大小时有可能采取的方法是把原来内存块上的所有数据复制到一个新的、更大的内存块上。当一个动态分配的内存块不再使用时,应该调用free 函数把它归还给可用内存池。内存被释放之后便不能再被访问。


The pointer returned by malloc, calloc, and realloc will be NULL if the requested allocation could not be performed. Erroneously accessing memory outside of an allocated block may cause the same errors as accessing memory outside of an array, but can also corrupt the pool of available memory and lead to a program failure.You may not pass a pointer to free that was not obtained from an earlier call to malloc,calloc, or realloc. Nor may you free a portion of a block.

如果请求的内存分配失败, malloc 、calloc 和realloc 函数返回的将是一个NULL 指针。错误地访问分配内存之外的区域所引起的后果类似越界访问一个数组,但这个错误还可能破坏可用内存池,导致程序失败。如果一个指针不是从早先的malloc 、calloc 或realloc 函数返回的,它是不能作为参数传递给free 函数的。你也不能只释放一块内存的一部分。


A memory leak is memory that has been dynamically allocated but has not been freed and is no longer in use. Memory leaks increase the size of the program,and may lead to a crash of the program or the system.

内存泄漏是指内存被动态分配以后,当它不再使用时未被释放。内存泄漏会增加程序的体积,有可能导致程序或系统的崩溃。