C——内存管理1
array limitations:
So there comes Dynamic memory allocation: Dynamic memory allocation?in C is a way of circumventing these problems. The standard C function? 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 is? 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]; ? 有时候在写程序的时候,我们不知道需要为我们的数据分配多少内存。在这种情况下,我们想要在程序已经开始运行后,为我们的程序动态分配其所需要的内存。?To do this we only need to declare a pointer,and invoke? 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 builtin? ? So how do we? ? int *array = malloc(10*sizeof(int));
? We only need to declare the pointer;? 重要警示!? It is not necessary to immediately call? int *array = NULL; printf("Hello World!!!"); /* more statements */ array = malloc(10*sizeof(int)); /* delayed allocation */ /* use the array */
Error checkingWhen we want to use? int *pt = malloc(3 * sizeof(int)); if(pt == NULL) { fprintf(stderr,"Out of memory,exitingn"); 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. The?
|