C Language Quick Explanation (iii) dynamic memory allocation

Source: Internet
Author: User

Preface: As an Android programmer, if do not understand C/s development, then Android JNI, NDK, video decoding, audio decoding can not be developed, there is a need for us to learn, come on. Today we start to quickly explain C language, Java based people are suitable to read this blog.

-----------Split Line--------

About the C language memory allocation is mainly:

1. Stack area (stack): Windows, stack memory allocation 2M, beyond the limit, Tip stack overflow error, can be automatically allocated and released (emphasis)

2. Heap Area (heap): We need to manually allocate and release, the largest operating system of 80% memory, that is, running memory. (emphasis)

3. Global or static area.

4. The character constants the quantity area.

5. program code to go.

-----------Split Line-------

This blog involves a case to be introduced in the header file:

#define _crt_secure_no_warnings
#include <stdio.h>
#include <stdlib.h>
#include < Windows.h>

--------Split Line--------

Stack memory, we manually allocate more than 40M memory to stack memory

Code:

void Main () {
	//40m
	//static memory allocation
	INT A[1024 * 1024 *];
	Stack memory
	GetChar ();
}
Run the display (360 will intercept if the 360 operation is turned on):


-----------Split Line-----------

To give you a clearer picture of what heap memory and stack memory are, see the following code:

Stack memory
void Stackfun () {
	int a[1024];
}
Heap memory
void Heapfun () {
	//40m memory
	//byte
	//void * pointer of any type
	int* p = malloc (1024 * 1024 *10 * sizeof (int)) c9/>//release
	//free (P);
}

void Main () {
	//on heap memory, allocating 40M of memory while
	(1) {Sleep
		(1000);
		Heapfun ();
		Stackfun ();
	}

	GetChar ();
}
Running the heap memory method inside the while loop, the task manager can observe that the presence has been increased (keep eating your memory, don't run too long)


Running the stack memory method inside the while loop, you can observe the memory in the Task Manager,


--------Split Line--------

Creates an array that dynamically specifies the size of the array.

Compared to Java: In the program running too long, you can randomly open up the specified size of memory for use, equivalent to the collection in Java

Static memory allocation: Allocated memory size is fixed,. 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: Dynamically specify the amount of memory that needs to be used while the program is running, manually released, and the memory can be reused after release

Code:

void Main () {
	//static memory allocation creates an array whose size is fixed
	//int i = ten;
	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 array's name
	//The array element is assigned a value (using this piece of memory area just opened up)
	int i = 0;
	for (; i < Len; i++) {
		P[i] = rand ()%;
		printf ("%d,% #x \ n", P[i], &p[i]);
	}
	
	Manual release of Memory Free
	(p);

	GetChar ();
}
Plus breakpoint debugging we can see


Then open the memory page and enter the first pointer address:


Tip: about how to pull up the above memory page: Step 1. Break point. 2. Run. 3. Debug-> window-> memory, 4. To set


----------Split Line----------

ReAlloc Memory Reallocation:

Two ways to reallocate 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

Code:

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 ()%;
		printf ("%d,% #x \ n", P[i],&p[i])
	;

	int Addlen;
	printf ("Please enter the length of the array added:");
	scanf ("%d", &addlen);
	Not enough memory to enlarge the memory space just allocated
	//ARG1: The original memory pointer arg2: The size of the memory after expansion
	int* P2 = realloc (p,sizeof (int) * (len + addlen));
	if (P2 = = NULL)
	{
		printf ("reassigning memory failed.") ");
	}
	Re-assign
	i = 0;
	printf ("--------------re-assign-------------------\ n");
	for (; i < Len+addlen; i++)
	{
		P2[i] = rand ()%;
		printf ("%d,% #x \ n", P2[i],&p2[i])
	;

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

	GetChar ();
}
Interrupt Point Run Display:


Memory Display:


Of course, if you want to shrink, then enter a negative number, of course, will also lose data.

----------Split Line--------

Memory allocation a few details to note:

1. Cannot be released multiple times (can be tested on its own)

2. After the release (the pointer still has a value), give the pointer null, flag release complete . Code:

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 ()%;
		printf ("%d,% #x \ n", P[i], &p[i]);
	}

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

	GetChar ();
}
3. Memory Leak (p after re-assignment, then free, and does not really release memory)。 Code:

void Main () {
	//40m
	int* p1 = malloc (1024 * 1024 * * sizeof (int));
	Free (p1);
	P1 = NULL;
	printf ("% #x \ n", p1);

	80M
	p1 = malloc (1024 * 1024 * sizeof (int) * 2);
	Free (p1);
	P1 = NULL;
	printf ("% #x \ n", p1);
	GetChar ();
}
Run production See Task Manager:

------------Finish------------





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.