Heap Stack (stack)

Source: Internet
Author: User
Tags printf
Memory allocation

In the C language, malloc () and realloc () complete the task of dynamically allocating memory. The allocated memory is in the heap, and the heap is an in-memory discontinuous area, and the memory allocation is realized by a linked list that records the free memory address.

Release memory using the free () function.

In C + +, use new to open up memory and use Delete to free up memory.

The allocation of heap memory is not sequential, as shown in the following program.

#include <stdio.h>
#include <stdlib.h>

int sum (int x,int y)
{
	int su;					local variable
	int su1;

	su = x+y;
	printf ("In the program stack: \ n");
	printf ("Local variable y address is%x\n", &y);
	printf ("The address of the local variable X is%x\n", &x);

	printf ("Local variable Su's address is%x\n", &su);
	printf ("Local variable SU1 address is%x\n", &su1);
	
	return su;
}

void Main ()
{

	int *a;
	int *b;
	int *c;
	A = (int *) malloc (sizeof (int) *10000);
	b = (int *) malloc (sizeof (int) *10000);
	c = (int *) malloc (sizeof (int) *10000);
	
	printf ("in heap: \ n");
	printf ("A's address is 0x%d\n", a);
	printf ("B's address is 0x%d\n", b);
	printf ("C's address is 0x%d\n", c);
	
	sum (in);

	Free (a);
	Free (b);
	Free (c);


}

Stack allocation is automatic control of the system, there is no specific function interface can be operated. As shown in the above program, local variables and function parameters exist in the stack and are stored continuously to the low address.

Space size

It is also possible to know that the stack and heap an important difference is that the heap to obtain memory space is more flexible, and the stack is to lower the address extension, so there will be a specific size limit.

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.