C Language memory allocation and release of the detailed

Source: Internet
Author: User
Tags array length constant rand


What is a heap? When it comes to heaps, I can't help talking about stacks! What is a stack?

1, what is the heap: The heap is a common space, divided into global heap and local heap. The global heap is all space that is not allocated, and the local heap is the space that the user allocates. The heap is allocated during the initialization of the process by the operating system, and can be added to the system during the run, but remember to return it to the operating system or memory leak.

2, what is the stack: the stack is unique to the thread, save its running state and local automatic variables. The stack is initialized when the thread starts, and each thread's stack is independent of each other. Each function has its own stack, which is used to pass arguments between functions. The operating system will automatically switch the stack when switching threads, which is to switch SS/ESP registers. Stack space does not need to be explicitly allocated and released within a high-level language.

C Language Program compilation of memory allocation, heap and stack differences:

Stack is automatically allocated by the compiler release, the function of the value of the parameters, local variables, and so on. The operation is similar to the stack in the data structure.
The heap is typically freed by the programmer and, if not freed, may be reclaimed by the OS at the end of the program. Note that this is possible, not necessarily. Once again, remember to release!
Stack area (stack):
Windows, stack memory allocation 2M (determined constants), exceeding the limit, prompting stack overflow error
The compiler automatically allocates and releases the parameters of the function, the values of local variables, etc.
Heap Area (heap): Programmers manually allocate release, operating system 80% memory

Global or static regions: storing global and static variables, releasing from the system at the end of the program, divided into global initialization zone and global uninitialized region;

Character constants: A constant String that is released by the system at the end of the program;

Program code area: the binary code that holds the function body.

Chestnuts:

int a=0; Global initialization Area
Char *p1; Global uninitialized Zone
void Main ()
{
int b; Stack
char s[]= "BB"; Stack
Char *p2; Stack
Char *p3= "123"; Where the "123\0" constant area, p3 in the stack area
static int c=0; Global Zone
p1= (char*) malloc (10); 10 byte area in the heap area
strcpy (P1, "123"); "123\0" in the constant area, the compiler may be optimized to point to the same area as the P3

}
Stack memory

void Stackfun () {
int a[1024];
Automatic stack Memory release
}
Heap Memory

void Heapfun () {
40M Memory
Bytes
void * pointers of any type
int* p = malloc (1024 * 1024 * sizeof (int));

Release
Free (p);
}
void Main () {
Allocate 40M of memory on heap memory
while (1) {
Sleep (1000);
Stackfun ();
}

GetChar ();
}
Creates an array that dynamically specifies the size of the array (in which the program runs too long and optionally opens up the specified size of memory for use, equivalent to a collection in Java)

Static memory allocation, allocating memory size is fixed, problem: 1. It is easy to exceed the maximum value of stack memory 2. In order to prevent the memory is not enough to open up more memory, easy to waste memory

Dynamic memory allocation, when the program is running, dynamically specify the amount of memory needed to use, manually released, after the release of these memory can also be reused (living water)

Function: Calloc () allocates memory space and initializes

The Calloc () function is used to dynamically allocate memory space and initialize to 0, which is modeled as:

void* calloc (size_t num, size_t size);
Calloc () dynamically allocates num contiguous space of size in memory and initializes each byte to 0. So it's the result of allocating the num*size byte-length memory space, and the value of each byte is 0.

The return value assignment successfully returns an address to that memory and returns NULL if it fails.

Functions: malloc () dynamically allocating memory space

malloc () function is used to dynamically allocate memory space (if you do not understand dynamic memory allocation, see: C Language Dynamic memory allocation and variable storage categories), the prototype is:

void* malloc (size_t size);
The code used in the program is as follows:

void Main () {
Static memory allocation creates an array, and the size of the array is fixed
int i = 10;
int a[i];

int Len;
printf ("Enter the length of the array:");
scanf ("%d", &len);

Open memory, size len*4 byte
int* p = malloc (len * sizeof (int));
P is the first address of the array, and P is the name of the array
Assigning values to array elements (using this piece of memory that just opened up)
int i = 0;
for (; i < len-1; i++) {
P[i] = rand ()% 100;
printf ("%d,% #x \ n", P[i], &p[i]);
}

Manually free memory
Free () frees dynamically allocated memory space
Free (p);

GetChar ();
}
ReAlloc Memory reallocation

void Main () {
int Len;
printf ("Length of first input array:");
scanf ("%d", &len);

int* p = malloc (len * sizeof (int));
int* p = calloc (len, sizeof (int));
int i = 0;
for (; i < Len; i++) {
P[i] = rand ()% 100;
printf ("%d,% #x \ n", P[i], &p[i]);
}

int Addlen;
printf ("Input array length added:");
scanf ("%d", &addlen);
Not enough memory to enlarge the memory space just allocated
1. The original memory of the pointer 2. Total size after memory expansion
int* P2 = realloc (p, sizeof (int) * (len + addlen));
if (P2 = = NULL) {
printf ("Redistribution failed, the world is so big, can't Hold Me ...") ");
}
Two cases of newly allocated memory:

Shrinking, shrinking that part of the data will be lost

To enlarge (a continuous)

1. If there is memory space behind the current memory segment, extend the memory space directly, realloc return the original pointer

2. If there is not enough free bytes behind the current memory segment, the first memory block in the heap that satisfies this requirement is used to copy the current data to the new location and release the original database and return the new memory address

3. If the request fails, return NULL, the original pointer is still valid

The code above is then assigned a new value
i = 0;
printf ("--------------------------\ n");
for (; i < Len + Addlen; i++) {
P2[i] = rand ()% 200;
printf ("%d,% #x \ n", P2[i], &p2[i]);
}

Manually free memory
if (P!= NULL) {
Free (p);
p = NULL;
}
if (P2!= NULL) {
Free (p2);
P2 = NULL;
}

GetChar ();
}
Memory allocation of several attention details

1. Cannot be released multiple times;

2. After the release (the pointer still has a value), give the pointer null, flag release completed;

3. Memory leak (p after redistribution, then free, and did not really release memory);

void Main () {
int Len;
printf ("Enter the length of the array:");
scanf ("%d", &len);

int* p = malloc (len * sizeof (int));
int i = 0;
for (; i < Len; i++) {
P[i] = rand ()% 100;
printf ("%d,% #x \ n", P[i], &p[i]);
}

if (P!= NULL) {
Free (p);
p = NULL;
}

GetChar ();
}

I just saw a simple question in a blog post:


Code1
char* Tostr ()
{
Char *s = "ABCDEFGHIJKL";
return s;
}
int main ()
{
cout << tostr () << Endl;
return 0;
}

Code2
char* Tostr ()
{
Char s[] = "ABCDEFGHIJKL";
return s;
}
int main ()
{
cout << tostr () << Endl;
return 0;
}

Two pieces of code are very simple, output a character, the type is different, one is char* string, one is char[] data.

And you know what? This I do know, I believe most people also know that there must be a bad, or two are not good to make!!! It's all right.

Result: The first correct output, the second output garbled.

Reason: In the scope of local variables and memory allocation problem, the first char* is to point to a constant, the scope is within the function, is assigned to the program's constant area, until the end of the program is destroyed, so the constant still exists before the end of the program. And the second is stored in the array, the scope is within the function, is allocated in the stack, will be the function call after the end of the release, then you call again, certainly wrong.

Memory allocation

What are local variables, global variables, and static variables?

As the name suggests, the local variable is in a limited range of variables, the scope is limited, for the program, in a function of the internal declaration of ordinary variables are local variables, local variables will be on the stack application space, after the function, the application space will be automatically released. The global variable, which is applied outside the function, is stored on the global (static area), knowing that the program ends before it is finished, so that its scope is the entire program. Static variables and global variables are stored the same way that the function body is declared static to make this variable work like a global variable, without worrying about the end of the function and being freed.

Related functions:


void *malloc (size_t size);
void free (void *p);

/* Commonly used in this way
Struct Elem *p;
p = (struct elem*) malloc (sizeof (struct elem))

void Free (P)
*/

malloc principle

The substance of the malloc function now, it has a so-called idle list that connects the available chunks of memory to a long listing. When the malloc function is invoked, it looks for a block of memory that is large enough to meet the user's request in the join table. The memory block is then split in half (the size of the piece is equal to the size of the user request, and the other is the remaining byte). Next, the memory assigned to the user is passed to the user, and the remaining piece, if any, is returned to the connection table. When the free function is invoked, it connects the memory blocks freed by the user to the idle chain. In the end, the free chain will be cut into a lot of small memory fragments, if the user requests a large memory fragment, then the idle chain may not be able to meet the user requirements of the fragment. As a result, the MALLOC function requests a delay and begins to rummage through the free chain to check each memory fragment, organize them, and merge the adjacent small free blocks into larger chunks of memory. If the required memory block is not available, the malloc function returns a null pointer, so be sure to make a return value when invoking the malloc dynamic request memory block.

Classification:

Stack--the compiler automatically assigns the release, holds the function's parameter value, the local variable value, and so on. The operation is similar to the stack in the data structure.
Heap Area (heap)-typically released by programmers, and if programmers do not release, the program may end up being reclaimed by the OS. Note that it is different from the heap in the data structure, and the distribution is similar to the list
Global zone (static area) (static)-the storage of global and static variables is placed in a piece, the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are adjacent to another area. The system is released after the program is finished.
Constant area-A constant string is placed here until the program is finished and released by the system. The problem is right here!!!
Code area-The binary code that holds the function body.
Direct handling of the code, indeed very good!! Easy to understand


Main.cpp
int a = 0; Global initialization Area
Char *p1; Global uninitialized Zone

Main ()
{
int b; Stack
Char s[] = "ABC"; Stack
Char *p2; Stack
Char *p3 = "123456"; 123456\\0 in the constant area, p3 on the stack.
static int c =0;//Global (static) initialization area
P1 = (char *) malloc (10);
P2 = (char *) malloc (20);//the area with 10 and 20 bytes allocated is in the heap area.
strcpy (P1, "123456"); 123456\\0 is placed in a constant area, and the compiler may optimize it with the "123456" that the P3 points to as a place.
}

In addition, there are realloc (reallocation memory), Calloc (initialized to 0), Alloca (application memory on the stack, automatic release) and so on.
The above is the C language in the allocation and release of memory, a number of commonly used functions ~

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.