C language memory management (malloc, calloc, free, relloc)

Source: Internet
Author: User

Memory Management


Custom type
Simply replace the original type name with a new type name


Typedef int Integer;
Int I, j;
Integer k;


// Declare the struct
Typedef struct {


Int month;
Int day;
Int year;
} Date; // use the struct of typedef life. The original struct variable is changed to a new type.


Date birthday;
Date * p;


// Define an array
Typedef int Num [100];
Num;


// Define the pointer
Typedef char * String
String p, s [10];


// Define the return value as a function pointer of the int type without Parameters
Typedef int (* pointer )();
Pointer p1, p2;


###
Typedef only specifies a new type name for an existing type, but does not create a new type.
Declare array type pointer type struct type shared body type Enumeration type with typedef
Typedef and # define have similarities on the surface
When the same type of data is used in different source files, typedef is often used to declare some data types. You can put all the typedef name declarations in a single header file.
The use of typedef names is conducive to general application and transplantation. Sometimes the program depends on the hardware features and the typedef type is convenient for transplantation.


------------------------------------------------------------------------


The bitfield definition is similar to the struct.
Format:
Struct bit domain structure name {

Type description bit Domain Name: Bit domain length;


}


The length of the bit field cannot exceed the number of digits of this type.
You can ignore other bits of this type.
It can be a non-bit domain name, indicating filling or adjusting the location


For example:
Struct sta {


Unsigned int a: 4; // occupies 4 bytes
Unsigned int: 0; // the remainder of the first byte in the airspace is completely cleared.
Unsigned int B: 4; // occupies 4 bytes
Unsigned int c: 4; // occupies 4 bytes


}
>>>>>


| A | null |
| B | c |

 

For example:
Struct stb {


Int a: 1; // occupies 1 digit
Int: 2; // indicates that two digits are not needed.
Int B: 3; // occupies 3 digits
Int c: 2; // occupies 2 digits


}


| A 1 | null 2 | B 3 | c 2 | // eight digits in total


------------------------------------------------------------------


Dynamic Memory Management
Non-static local variables are allocated to the dynamic storage area in the memory, which is a region called Stack.


For example, int a is stored in the stack area.


The C language also allows the establishment of dynamic distribution areas to store some temporary data, the data needs to be opened up at any time, do not need to try to release, the data is temporarily stored in a special
As a heap zone.


For example, static variables in manual allocation units of global variable memory management all exist in the heap zone.


Static and Dynamic
Static Memory Allocation is performed before the program is executed, so the efficiency is relatively high. However, it lacks flexibility and requires you to know the type and quantity of memory required before the program is executed.
A static object is a variable with a name. We perform operations directly on it, while a dynamic object is a variable without a name. We perform operations on it indirectly through a pointer.
Static objects are automatically released by the compiler, and dynamic variables need to be manually released.


Method:


Malloc
Calloc
Free
Realloc


1. malloc (size) allocated to heap
Void * malloc (usingned int size); unit: (bytes) bytes
The function is to allocate a length side space in the dynamic storage area of the content. This function is a pointer-type function, and the returned pointer is the position (or first address) at the beginning of the allocation area)
Note that the pointer type bit void does not point to any type of data and only provides one address. The type of data to be placed, and the type of mandatory conversion bit.
If the function fails to apply for space (insufficient memory), NULL pointer is returned.


For example:
// Allocate 40 bytes of continuous space to point a to the first address of the new space
Int * a = (int *) malloc (40 );
// Determine whether the application is successful
If (a = NULL ){


}


======================================
Exercise: Apply for two Student types of space


Struct Student stu;
* P = (struct * Student) malloc (sizeof (struct Strdent) * 2 );
// Judge
If (p = NULL ){


}


Another type: typedef
Typedef struct Student {


.....
......
} Stu;


Stu * p = (stu *) malloc (sizeof (stu) * 2 );
// Judge
If (p = NULL ){


}
======================================


2. calloc (quantity, size) is allocated to the heap Zone


Viid * calloc (unsigned n, unsigned size); int a = sizeof (stu); stu * B = (stu *) calloc (2, );
The function is to allocate n consecutive spaces with length bits in the dynamic storage area of the memory. This space is generally large enough to store an array.
Dynamic Storage space can be opened for one-dimensional arrays. n is the number of array elements, and the length of each element is the size. This is a dynamic array.


Calloc -----> malloc
For example: calloc (m, n) ----> malloc (m * n );


Malloc -----> calloc
For example: malloc (a) ----> calloc (1, );


For example: int * a = (int *) calloc (10, sizeof (int); if (a = NULL) 40 bytes, equal to allocating a one-dimensional array with a length of 10

 


3. free (pointer variable)
Void free (void * p); p = NULL;
The function is to release the dynamic space pointed to by the pointer Variable p, which can be used by other variables again. p should be the return value of the function obtained when the calloc or malloc function is called the last time.
Free (p) releases the allocated dynamic space pointed to by the pointer Variable p, but note that when p is released, p becomes a wild pointer, therefore, you must add a p = NULL or p = 0;
No return value for the free function
After the dynamically allocated space is used up, it must be released.


* ***** Note *****
When using malloc or cmalloc to apply for a space, for example, int * p = (int *) malloc (40 );
The p pointer cannot be ++ p or -- p, which will cause some memory areas to be unable to be returned, resulting in Memory leakage.


4. realloc (pointer, size)
Void * realloc (void * p, unsigned int size );
If you have obtained dynamic space through the malloc function and want to change the size, you can use the relloc function to re-allocate the space.
With the realloc function, the size of the dynamic space pointed to by p is changed to size, and the value of p remains unchanged. If the reallocation fails, NULL ("p = (int *) relloc (p, 20) "This sentence has a problem. Once the reallocation fails, p = NULL will lead to the failure to find the original space pointed by p and return failure, leading to memory leakage );

Related Article

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.