//
you're reading...
C++/C

Memory allocation and variables in C language

Program1

char* toStr()   
{  
    char *s = "abcdefghijkl";  
    return s;  
}
   
int main()  
{  
    cout << toStr() << endl;  
    return 0;  
}  

Program2

char* toStr()   
{  
    char s[] = "abcdefghijkl";  
    return s;  
}
   
int main()  
{  
    cout << toStr() << endl;  
    return 0;  
}

Program1 print out the string, program2 print out a piece of code is garbled. I remember when talked about learning C language, the string is treated as an array of characters to deal with. So character array name is equivalent to a pointer pointing to the first address.

char *s = "abcdefghijkl";
char s[] = "abcdefghijkl";

Both statements should return same results, but why the 2 programs output different results ? The reason is that there is no good understanding of memory allocation.

The first expression, the pointer s is a local variable within the scope of his functions toStr. It points to address its return, after returning s namely destruction, fortunately the point of address is returned back. Final printed correctly.

The second expression, why it is different between the first and the second, where is wrong? The reason is that although the first pointer s local variables, stack space is allocated, the scope is inside a function, but it points to the content “abcdefghijkl” is a constant, the constant is assigned in the program area. Until the end of the whole procedure was only destroyed. While the second, s is an array, stack space allocated to, “abcdefghijkl” as an array element is placed in each array, once the function exits, the stack is released this memory. Although the return address, but has lost its meaning.

First, we need to figure out: the type of variable and its storage type are two different concepts. Data types and memory management don’t have a direct relationship.

The C/C++ compiler’s memory usage is divided into the following sections:

  • stack – assigned automatically by the compiler release, storage function parameters, local variables and so on. Its mode of operation is similar to the data structure of the stack.
  • heap – general distribution release by the programmer, if the programmer does not release, may be recovered by the OS when the program ends. Note that this data structure heap are two different things, distribution lists actually like, huh, huh.
  • static – global variables and static variables are stored on a piece of global variables and static variables are initialized in an area, uninitialized global variables and static variables are not initialized in the adjacent another one region. Released by the system after the end of the program.
  • literal area – constant string is placed here. Released by the system after the end of the program
  • program code area – the binary code stored function body.
//main.cpp    
int a = 0; //Global initialization area  
char *p1; //Global uninitialized area  
       
main()  
{  
    int b; //stack  
    char s[] = "abc"; //stack  
    char *p2; //stack
    char *p3 = "123456"; //123456 \\ 0 in the constant region,p3 on on stack
    static int c =0;// The global (static) initialization area
    p1 = (char *)malloc(10);      
    p2 = (char *)malloc(20);//Get more distribution areas 10 and 20 bytes in the heap area
    strcpy(p1, "123456"); //123456\\0 On the constant region, the compiler might it pointed p3 "123456" optimized for a place        
}   

How to apply for memory

stack: automatically assigned by the system. For example, declare a local variable in the function

int b

the system automatically allocate the memory space b in stack

heap: programmers need to apply their own, and specify the size, malloc function of the c

For Example

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

p1 = (char *)malloc(10); 

Notice: The variable p1 is store in stack space.

In response to the application of the system

stack: stack only remaining space is larger than the space application system will provide program memory, otherwise it will report an exception in the stack overflow

heap: First of all should know the operating system has a linked list of free memory address of record, When the system receives an application of memory allocation, will traverse the list to find the heap node is greater than the first space application space; then, the node is removed from the list of free nodes, and the spatial distribution of the node to the program. In addition, for most systems, this will be the first address in the memory space allocated record of this size, Only in this way, the code delete statement can release this memory space correctly. Due to the size of the heap has been found in node is not necessarily equal to the size of the application of the memory allocation exactly, the system will automatically return that part of the surplus back into the free list.

Limit the size of the application

stack: In Windows, the stack is extended to low-address data structure, It is a contiguous area of memory. This means that the maximum capacity of the stack address and stack the system predetermined good, Under WINDOWS, the stack size is 2M. If space applications exceeds the remaining space of the stack, you will be prompted overflow. Thus, less space obtained from the stack.

heap: heap is extended to high-address data structure is not continuous memory area. This is because the system is used to store the list of free memory address, nature is not continuous, and the list traversal direction is from low to higher addresses. Heap size is limited to the computer system and effective virtual memory. Thus, the space available heap more flexible, but also relatively large.

It is not a large array of variables in the program automatically (internal function), because of the limited stack (which is the stack segment of the program, we usually say, a large array overflow occurs segment) in size, and can apply to a global variable, because it is allocated in the static area, the size is unlimited.

Compare application efficiency

Stack is automatically assigned by the system faster. But the programmer can not control.

Heap memory allocated by new, usually more slowly, and prone to memory fragmentation, but it most convenient to use.

Heap and stack memory contents

stack: the function call, the first into the stack is the main function after the next instruction (the next function call statement executable statement) address, and then the function of various parameters, in most C compilers , the parameters are pushed onto the stack from right to left, then a function of the local variables. Note that the static variable is not pushed on.

When the end of the second function call, first-out stack of local variables, then parameter, the last top of the stack pointer to the beginning of stored address, which is the main function of the next instruction, the program continues to run by that point.

heap: heap is generally the head of the store with a byte size of the heap. The specific content of the heap programmers arrangements.

Compare access efficiency

char s1[] = "aaaaaaaaaaaaaaa"; 
char *s2 = "bbbbbbbbbbbbbbbbb"; 

‘aaaaaaaaaa’ is assigned at runtime

And ‘bbbbbbbbbbb’ is determined at compile time

However, after the access, the array on the stack pointer points faster than the string (eg heap). For Example:

#include <stdio.h> 
void main() 
{ 
	char a = 1; 
	char c[] = "1234567890"; 
	char *p = "1234567890"; 
	a = c[1]; 
	a = p[1]; 
	return; 
} 
Advertisements

About daviewning

I am an Oracle DBA

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: