C——内存管理1,如何实现高效且稳定的内存管理策略?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1105个文字,预计阅读时间需要5分钟。
数组限制:数组大小必须在程序开始前确定,且在程序运行期间不能更改。因此,出现了动态内存分配:C语言中的动态内存分配是一种绕过这种限制的方法。
array limitations:
- the size of the array must be known beforehand
- the size of the array cannot be changed in the duration of your program
So there comes Dynamic memory allocation:
Dynamic memory allocationin C is a way of circumventing these problems.
The standard C functionmalloc function 定义在 stdlib.h or malloc.h 中,取决于你使用的操作系统。
Malloc.h contains only the definitions for the memory allocation functions and not the rest of the other functions defined in stdlib.h.Usually you will not need to be so specific in your program, and if both are supported, you should use <stdlib.h>, since that is ANSI C, and what we will use here.
The corresponding call to release allocated memory back to the operating system isfree. When dynamically allocated memory is no longer needed,freeshould be called to release it back to the memory pool.
Overwriting a pointer that points to dynamically allocated memory can result in that data becoming inaccessible. (对于指向动态分配的内存的指针,指向最好不要发生变化,否则会导致动态分配的内存里的数据无法被获取。)If this happens frequently, eventually the operating system will no longer be able to allocate more memory for the process. Once the process exits, the operating system is able to free all dynamically allocated memory associated with the process.
create an array:
int array[10]; /* arraycan be considered a pointer which we use as an array. */
有时候在写程序的时候,我们不知道需要为我们的数据分配多少内存。在这种情况下,我们想要在程序已经开始运行后,为我们的程序动态分配其所需要的内存。To do this we only need to declare a pointer, and invokemallocwhen we wish to make space for the elements in our array,or, we can tellmallocto make space when we first initialize the array. Either way is acceptable and useful.
We also need to know how much an int takes up in memory in order to make room for it; fortunately this is not difficult, we can use C‘s builtinsizeofoperator. For example, ifsizeof(int)yields 4, then oneinttakes up 4 bytes. Naturally,2*sizeof(int)is how much memory we need for 2ints, and so on.
So how do wemallocan array of tenints like before? If we wish to declare and make room in one hit, we can simply say
int *array = malloc(10*sizeof(int));
We only need to declare the pointer;mallocgives us some space to store the 10ints, and returns the pointer to the first element, which is assigned to that pointer.
重要警示!malloc并不初始化 array; this means that the array may contain random or unexpected values! Like creating arrays without dynamic allocation, the programmer must initialize the array with sensible values before using it. Make sure you do so, too. (See later the functionmemsetfor a simple method.)
It is not necessary to immediately callmallocafter declaring a pointer for the allocated memory. Often a number of statements exist between the declaration and the call tomalloc, as follows:
int *array = NULL; printf("Hello World!!!"); /* more statements */ array = malloc(10*sizeof(int)); /* delayed allocation */ /* use the array */
Error checking
When we want to usemalloc, we have to be mindful that the pool of memory available to the programmer isfinite. As such, we can conceivably run out of memory! In this case,mallocwill returnNULL. In order to stop the program crashing from having no more memory to use, one should always check that malloc has not returnedNULLbefore attempting to use the memory; we can do this by
int *pt = malloc(3 * sizeof(int)); if(pt == NULL) { fprintf(stderr, "Out of memory, exiting\n"); exit(1); }
Of course, suddenly quitting as in the above example is not always appropriate, and depends on the problem you are trying to solve and the architecture you are programming for. For example, if the program is a small, non critical application that‘s running on a desktop quitting may be appropriate. However if the program is some type of editor running on a desktop, you may want to give the operator the option of saving their tediously entered information instead of just exiting the program. A memory allocation failure in an embedded processor, such as might be in a washing machine, could cause an automatic reset of the machine. For this reason, many embedded systems designers avoid dynamic memory allocation altogether.
Thecallocfunction
Thecallocfunction allocates space for an array of items and initializes the memory to zeros. The callmArray = calloc( count, sizeof(struct V))allocatescountobjects, each of whose size is sufficient to contain an instance of the structurestruct V. The space is initialized to all bits zero. The function returns either a pointer to the allocated memory or, if the allocation fails,NULL.
本文共计1105个文字,预计阅读时间需要5分钟。
数组限制:数组大小必须在程序开始前确定,且在程序运行期间不能更改。因此,出现了动态内存分配:C语言中的动态内存分配是一种绕过这种限制的方法。
array limitations:
- the size of the array must be known beforehand
- the size of the array cannot be changed in the duration of your program
So there comes Dynamic memory allocation:
Dynamic memory allocationin C is a way of circumventing these problems.
The standard C functionmalloc function 定义在 stdlib.h or malloc.h 中,取决于你使用的操作系统。
Malloc.h contains only the definitions for the memory allocation functions and not the rest of the other functions defined in stdlib.h.Usually you will not need to be so specific in your program, and if both are supported, you should use <stdlib.h>, since that is ANSI C, and what we will use here.
The corresponding call to release allocated memory back to the operating system isfree. When dynamically allocated memory is no longer needed,freeshould be called to release it back to the memory pool.
Overwriting a pointer that points to dynamically allocated memory can result in that data becoming inaccessible. (对于指向动态分配的内存的指针,指向最好不要发生变化,否则会导致动态分配的内存里的数据无法被获取。)If this happens frequently, eventually the operating system will no longer be able to allocate more memory for the process. Once the process exits, the operating system is able to free all dynamically allocated memory associated with the process.
create an array:
int array[10]; /* arraycan be considered a pointer which we use as an array. */
有时候在写程序的时候,我们不知道需要为我们的数据分配多少内存。在这种情况下,我们想要在程序已经开始运行后,为我们的程序动态分配其所需要的内存。To do this we only need to declare a pointer, and invokemallocwhen we wish to make space for the elements in our array,or, we can tellmallocto make space when we first initialize the array. Either way is acceptable and useful.
We also need to know how much an int takes up in memory in order to make room for it; fortunately this is not difficult, we can use C‘s builtinsizeofoperator. For example, ifsizeof(int)yields 4, then oneinttakes up 4 bytes. Naturally,2*sizeof(int)is how much memory we need for 2ints, and so on.
So how do wemallocan array of tenints like before? If we wish to declare and make room in one hit, we can simply say
int *array = malloc(10*sizeof(int));
We only need to declare the pointer;mallocgives us some space to store the 10ints, and returns the pointer to the first element, which is assigned to that pointer.
重要警示!malloc并不初始化 array; this means that the array may contain random or unexpected values! Like creating arrays without dynamic allocation, the programmer must initialize the array with sensible values before using it. Make sure you do so, too. (See later the functionmemsetfor a simple method.)
It is not necessary to immediately callmallocafter declaring a pointer for the allocated memory. Often a number of statements exist between the declaration and the call tomalloc, as follows:
int *array = NULL; printf("Hello World!!!"); /* more statements */ array = malloc(10*sizeof(int)); /* delayed allocation */ /* use the array */
Error checking
When we want to usemalloc, we have to be mindful that the pool of memory available to the programmer isfinite. As such, we can conceivably run out of memory! In this case,mallocwill returnNULL. In order to stop the program crashing from having no more memory to use, one should always check that malloc has not returnedNULLbefore attempting to use the memory; we can do this by
int *pt = malloc(3 * sizeof(int)); if(pt == NULL) { fprintf(stderr, "Out of memory, exiting\n"); exit(1); }
Of course, suddenly quitting as in the above example is not always appropriate, and depends on the problem you are trying to solve and the architecture you are programming for. For example, if the program is a small, non critical application that‘s running on a desktop quitting may be appropriate. However if the program is some type of editor running on a desktop, you may want to give the operator the option of saving their tediously entered information instead of just exiting the program. A memory allocation failure in an embedded processor, such as might be in a washing machine, could cause an automatic reset of the machine. For this reason, many embedded systems designers avoid dynamic memory allocation altogether.
Thecallocfunction
Thecallocfunction allocates space for an array of items and initializes the memory to zeros. The callmArray = calloc( count, sizeof(struct V))allocatescountobjects, each of whose size is sufficient to contain an instance of the structurestruct V. The space is initialized to all bits zero. The function returns either a pointer to the allocated memory or, if the allocation fails,NULL.

