Getting Started with C programming-dynamic memory allocation

Source: Internet
Author: User

Memory management refers to the technology of allocating and using computer memory resources when the software is running. Its primary purpose is to efficiently and quickly allocate and to release and reclaim memory resources when appropriate. Memory management is an important part of C programming, C language memory needs to be manually allocated, manually released, generally follow the allocation of how much, how much to release, so as not to cause memory leaks. Memory management is an important and complex thing, and understanding memory management can play a major role in the learning of later courses and projects.

Previously created variables, is the system automatically allocated memory, placed in the stack memory, destroyed by the system automatically reclaimed, manually allocated memory, placed in the heap memory, need to manually release. Never forget to destroy objects manually freeing the memory and placing the pointer empty (NULL).

Memory allocation Common header file: malloc.h


malloc function:

# include <stdio.h># include <malloc.h>int main (void) {int i = 3;//Static allocation of memory, assigning 4 byte space to variable i. int * p = (int *) malloc (20); /*1. To dynamically allocate memory, to use the malloc function, you must add the malloc.h header file. malloc is the abbreviation for memory (RAM)    allocate (allocation). 2. The malloc function has only one formal parameter, and the formal parameter is an integral type. 3.20 indicates that the request system allocates 20 bytes of memory space for this program. 4. The return value of the malloc function is the memory address of the first byte, assigned to the pointer variable p.   The return value of the malloc function is the void * type, and the void * Type is also called a dry address, which is no meaningful address.   and you need to force the type conversion (int *) to convert the allocated memory to the int * type defined by the pointer variable p. A   total of 20 bytes are allocated, each of which is 4 bytes, so it coexists with 5 variables (dynamic arrays). The   first variable is *p, the second is * (p+1), and so on, and I is a * (p+i). 5. Note: The pointer variable p occupies 4 bytes of memory, is statically allocated, and P points to the memory that is dynamically allocated. */*p = 3; The first variable is assigned a value of (p+1) = 5; Assign a value of 5printf ("%d,%d\n", *p, * (p+1)) to the second variable, and free (p); The free () function frees the memory space that P points to. Note: The memory space of P itself is static and will not be released, but can only be released by the system at the end of the program. return 0;}


To statically allocate memory:

# include <stdio.h># include <malloc.h>int main (void) {printf ("Hehe! \ n "); while (true) {int * p = (int *) malloc (+);  Infinite loop allocating memory}return 0;}


The free function:

# include <stdio.h># include <malloc.h>//free () functions are also located in the malloc.h header file, so be declared. int main (void) {int i = 3;int * p = &i;free (P); The memory of the variable I pointed to by//p is statically allocated and cannot be released manually, so the write error occurs. printf ("%d\n", I); return 0;} Run a direct error


To construct a one-dimensional array dynamically:

# include <stdio.h># include <malloc.h>int main (void) {int a[5];//statically constructs a one-dimensional array of 5 elements. int * Parr;int len;int i;printf ("Please enter the number of elements to be stored:"), scanf ("%d", &len);p arr = (int *) malloc (4*len); A one-dimensional array is constructed dynamically, Len is the length, the array type is of type int, and the array name is Parr. Similar to int a[5]; The array name Parr is the same as a. The operation of a dynamic array is the same as a static array, where the array name Parr the address of the first element of the array. for (i=0; i<len; ++i) {printf ("Enter the value of%d elements:", I); scanf ("%d", &parr[i]);//same as static array operations. }printf ("contents in one-dimensional array: \ n"); for (i=0; i<len; ++i) printf ("a[%d] =%d\n", I, Parr[i]); ReAlloc (parr,100); ReAlloc () re-allocates memory functions to change the length of the array, followed by two parameters, the first is the array name, the second is the number of reassigned array bytes,   //So the function will parr the memory of the array to 100 bytes.   //When memory changes, growth: such as 50 bytes to 100 bytes, the first 50 bytes content remains unchanged, and then add 50 bytes of memory.   //   shrink: such as 150 bytes to 100 bytes, first 100 bytes content reserved, and after 50 bytes content is lost. Free (PARR); The free () function frees the variable memory that the pointer variable points to, and when the array name is freed, it frees up the memory of the entire array, rather than just the first element variable memory pointed to by the array name. printf ("Content in one-dimensional array: \ n"); for (i=0; i<len; ++i) printf ("a[%d] =%d\n", I, Parr[i]); return 0;}

Dynamic memory is used across functions:

Pass the pointer variable past

# include <stdio.h>void f (int * * q) {int i = 5;*q = &i;return;} int main (void) {int * P;F (&p);p rintf ("%d\n", *p);//This is logically wrong, because the function f () has already run to the end, p points to the variable i has been released, no longer exists, can not read the output again. The reason the program did not error is because the software (vc++6.0) is more mentally retarded. return 0;}


Dynamic memory Cross function use 2:

/*2013 January 27 21:05:44 The use of dynamic memory across functions  (which need to be addressed when used) is constructed in the main () function to assign values in the change () function to output */# include in the printf () function <stdio.h ># include <malloc.h>void change (int * q) {*q = 10;return;} void printf (int * r) {printf ("%d\n", *r); return;} int main (void) {int * p = (int *) malloc (sizeof (int));//construct dynamic memory variable. *p = 3;change (P);p rintf (p); return 0;}


Practice Examples:

# include <stdio.h># include <malloc.h>int main (void) {Double i = 66.6;double * p = &i;printf ("%d\n", Sizeo F (*p));p = (double *) malloc (sizeof (double)); *p = 88.8; Free (p); The memory space pointed to by the pointer variable p cannot be re-released, that is, the wild pointer can no longer be released, resulting in an error. return 0;}





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Getting Started with C programming-dynamic memory allocation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.