Reprinted please note address: http://www.openext.org/2014/04/stackheap/
Stack is related to system design and managed by the system. However, programmers can get the memory in the heap by using the new malloc statement.
Stack is a continuous memory area that grows down. The stack size is set by the system. Heap is an area of continuous memory that grows up. Because the operating system uses a linked list to manage memory.
The heap size is limited by the system's valid virtual memory.
STACK: when calling a function, the first entry to the stack is the address of the next instruction after the function is called in the main function, and then the parameters of the function. Note that static variables are not included in the stack. When this function call ends, local variables first go out of the stack,
Then there is the parameter, and the top pointer of the final stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.
Heap: The specific content in the heap is arranged by the programmer.
General example
Int a = 0; global initialization Zone
Char * p1; uninitialized globally
Main ()
{
Int B; stack
Char s [] = "abc"; stack
Char * p2; stack
Char * p3 = "123456"; 123456 \ 0 is in the constant zone, and p3 is in the stack.
Static int c = 0; Global (static) initialization Zone
P1 = (char *) malloc (10); heap
P2 = (char *) malloc (20); heap
}
Int main (){
Char * p1 = "helloworld ";
Char * p2 = "helloworld ";
Char p3 [] = "helloworld ";
Char p4 [] = "helloworld ";
Printf ("0x % 08x \ n", p1 );
Printf ("0x % 08x \ n", p2 );
Printf ("0x % 08x \ n", p3 );
Printf ("0x % 08x \ n", p4 );
}
Output result:
Test @ ubuntu :~ $./A. out
0x0040072c
0x0040072c
0xc3340450
0xc3340460
Because the pointer p1 and p2 point to the data stored in the constant area, and because they are the same value, the p1 and p2 values are the same.
Although the content of p3 and p4 is the same, all the addresses of the character arrays on the stack are different.