Common programming problems (i) less large number plus minus

Source: Internet
Author: User

Concept of storage Area

Common storage areas can be divided into:

    • Stack

The store of variables that are allocated by the compiler when needed and automatically purged when not needed. The variables inside are usually local variables, function parameters, and so on.

    • Heap

By new allocating the memory blocks, their release compiler does not go to the tube, which is controlled by our application, and the general one is new going to correspond to one delete . If the programmer does not release, the program will always take up memory, causing a memory leak, after the program ends, the operating system will be automatically recycled.

A malloc block of allocated memory, which is very similar to a heap, but it is used free to release allocated memory.

    • Global/Static Storage area

Global variables and static variables are allocated in the same piece of memory, in the previous C language, the global variables are divided into initialized and uninitialized, in which C++ there is no such distinction, they collectively occupy the same piece of memory area.

    • Constant Storage Area

This is a very special storage area, they are stored in a constant, not allowed to modify (of course, you have to pass the improper means can also be modified).

    • Code snippet: A binary code that holds the body of a function.

Example 1: C language Programs

int x;  void main()  {  }  

xWhat area is the variable stored in memory?

A: In a segment-based memory management architecture, BSS segment ( bss segment ) is usually a chunk of memory that is used to hold uninitialized global variables in the program.

BSSIt is Block Started by Symbol the abbreviation of English. BSSsegments belong to the static storage area.

Example 2: static What is the difference between a global variable and a normal global variable?

A: static the global variable and the normal global variable storage area are the same, the difference is:

staticGlobal variables are only valid in the file that declares this static global variable;

Normal global variables are valid for the entire source program , and when the source program contains more than one file, it is still valid for other files.

Example 3: What static is the difference between a local variable and a normal local variable?

A: The storage area of static local variables is static storage area, the storage of ordinary local variables is stack;

staticA local variable lifetime is the entire source program, but it can only be called in the function that declares it , and its value is related to the last result, whereas the lifetime of a normal local variable is the period of declaring its function, and its value is reinitialized over a specific range;

staticLocal variables are undefined if they are not initialized by default 0 , while ordinary local variables are not.

//main.cppINTA =0;//Global initialization ZoneChar*P1;//Global uninitialized zoneMain () {intb//Stack    CharS[] ="ABC";//Stack    Char* P2;//Stack    Char* P3 ="123456";//123456\0 in the constant area, p3 on the stack.     Static intc =0;//Global (Static) initialization zoneP1 = (Char*)malloc(Ten); P2 = (Char*)malloc( -);//Allocated 10 and 20 bytes of the area are in the heap area. }
The difference between stacks

1. Memory allocation:

Heap: Typically released by programmers, if the programmer does not release, the program may end up being OS recycled. Note that it is different from the heap in the data structure, and the distribution is similar to a linked list. The following keywords may be used: new ,, malloc , delete and free so on.

Stack: Automatically allocated by the compiler ( Compiler ) release, store the function parameter value , local variable value and so on. It operates in a manner similar to a stack in a data structure.

2. Method of application:

Heap: Requires programmers to apply themselves and indicate size. In c the malloc function. As in the p1 = (char *)malloc(10); C++ new operator, but note that p1 p2 itself is in the stack. Because they can still be considered as local variables.

Stack: Automatically assigned by the system. For example, a local variable is declared in a function, and the int b system automatically opens up space in the stack b .

3. System response:

Heap: The operating system has a list of idle memory address, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the application space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program, in addition, for most systems, will The size of this allocation is recorded at the first address in this memory space , so that the statements in the code delete can properly free up the memory space. In addition, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list, which can lead to memory fragmentation.

Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.

4. Size limitation:

Heap: Is the data structure that extends to the high address , which is a discontinuous memory area . This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

Stack: In the Windows bottom, the stack is the data structure to the low address extension , which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined , in the WINDOWS next, the size of the stack is fixed (is a compile-time determination of the constant), if the requested space exceeds the stack's remaining space, will be prompted overflow . Therefore, the space available from the stack is small.

5. Efficiency:

Heap: is new allocated by the memory, the general speed is relatively slow, and easy to produce memory fragmentation , but the most convenient to use.

Stack: Automatically allocated by the system, faster. But programmers can't control it.

6. Contents of storage:

Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

Stack: The address of the first stack in the function call is the next instruction in the main function (which will continue to execute from this instruction when returning from the function) (the next executable statement of the function call statement) and then the parameters of the function, in most C compilers, The argument is a right-to-left stack, followed by a local variable in the function. Note: Static variables are not in the stack . when the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point .

7. Access efficiency:

Heap: char *s1 = "Hellow Word" ; is determined at compile time;

Stack: char s1[] = "Hellow Word" ; it is assigned at run time; it is faster to use an array than a pointer, because the pointer needs to be in a register in the underlying assembly edx , and the array is read directly on the stack.

Methods for exchanging two values

There are three ways to do this:

void Swap1 (int *a,int *b)//First, also the most common type of {intT t =*a;*a=*b;*b= t;} void Swap2 (int *a,int *b//second, no additional memory space required (no temporary variable) {*a=*a+*b;*b=*a-*b;*a=*a-*b;} The above method may lead to cross-border, why not use the difference between their two? void Newswap2 (int *a,int *b){*a=*b-*a;*b=*b-*a;*a=*a+*b;} The above code is an arithmetic process to achieve the exchange of values of A and B. The main method here is to consider the median |a-b| and leave an original value. However, to make the program correct, but also to do some value of the size of judgment. Writing a function would be cumbersome and universal. void Swap3 (int *a,int *b//Third, does not require additional memory space, bit operation implementation {*a^=*b;*b^=*a;*a^=*b;} The method of exchange here is also dependent on the formula A^b^a=b and a^b^b=a the law. However, the transfer of function parameters is divided into two kinds of value passing and address passing. Therefore, the exchange also has two kinds, the value exchange and the variable points to the value of the address exchange. can only swap integers (charintLong), to exchange two floating-point numbers is not possible, because the floating-point number can not participate in bit operations, to exchange two pointers is also not possible, the compiler does not allow you to take two pointers to do bit operations, to exchange two user-defined objects is also not possible, because it still cannot participate in bit operation

The purpose of this value exchange is to reduce the request for temporary variables and to reduce the memory space required by the program. It is a good solution for a large number of applications to apply temporary variables to implement the Exchange program.

Large number plus minus (high efficiency)

Common programming problems (i) less large number plus minus

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.