Difference between C/C++ heap and stack

There are five main differences between C/C++ heap and stack

1. Different life cycles

Heap: Generally allocated and released by the programmer. If the programmer does not release it, it will be reclaimed by the OS when the program ends.

Stack: Automatically allocated by the compiler

2. The application method is different

Heap: To use a heap space in a program, you can use the new keyword, malloc function, calloc() function, and realloc function. When this heap space is not needed, you can use the delete keyword and free function.

Stack: automatically allocated by the system

3. The underlying implementation mechanism is different

Heap: The growth direction grows upward. Generally, the storage space is managed through a linked list, and the memory can be discontinuous.

Stack: The growth direction is downward (some systems may grow upward), and the space usage is continuous

4. The size of the application space is different

Heap: Limited by the effective virtual memory in the computer system, on a 32-bit system, its size can be up to 4G

Stack: Under Windows, the size of the stack is fixed (it is a constant determined at compile time), so it is not suitable for programmers to apply for too much stack space in the function, otherwise it will cause the program stack to overflow

5. Different memory utilization

Heap: space utilization is generally random and discontinuous memory space, which is prone to memory fragmentation

Stack: allocated by the system, faster


A concrete instance of stack allocation:

#include <iostream>//Input and output stream library
#include <string>//String processing library
#include <iomanip> //Format control character library for output stream
#include <cstdlib>
 
using namespace std;//Release all objects in the std namespace

int a=0;//Global initialization area
char *p1;//Global uninitialized area

int main(void)
{
	int b; // stack
	char s[]='abc';// stack
	char *p2; //stack
	char *p3='123456';//stack
	chat *p4; //stack
	static int c=0;//Global (static) initialization area

	p1=(char*)malloc(10);//Allocate 10 bytes in the heap
	p2=(char*)malloc(20);//Allocate 20 bytes in the heap
	p4=new char[10];//Allocate 10 bytes in the heap and put the first address in the p4 stack

	strcpy(p1,'abcdefg');//Put "abcdefg\0" in the constant area
//The following ways of freeing space are the same
	free(p1);
//Because the space pointed to by p3 is not a heap space, it cannot be released manually, which will cause an error
//	free(p3);

	delete p2;
	delete[]p4;

	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324655073&siteId=291194637