C language char[] and char* comparison

Source: Internet
Author: User

Let's take a look at one example:

1#include <iostream>2 using namespacestd;3  4 Main ()5 {6    Char*C1 ="ABC";7    CharC2[] ="ABC";8    Char*C3 = (Char*) malloc (3);9C3 ="ABC";Tenprintf"%d%d%s\n",&c1,c1,c1); Oneprintf"%d%d%s\n",&c2,c2,c2); Aprintf"%d%d%s\n",&c3,c3,c3); - GetChar (); -}

Test environment devc++

The results of the operation are as follows:
2293628 4199056 ABC
2293624 2293624 ABC
2293620 4199056 ABC

//==================================================//

Resources:
The first thing to figure out is the partitioning of the memory that the compiler occupies:


I. Preliminary knowledge-memory allocation of the program
The memory used by a program compiled by C + + is divided into the following sections
1. Stack (stack)-Automatically allocated by the compiler to 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, Heap area (heap)-generally by the programmer assigned to release, if the programmer does not release, the end of the program may be recycled by the OS. Note that it is not the same as the heap in the data structure, the distribution is similar to the list, hehe.
3. Global Zone (static zone)-the storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another contiguous area. Released by the system after the program is finished.
4, literal constant area -the constant string is put here. Released by the system after the program is finished.
5. Program code Area
It was written by a predecessor, very detailed

1 //main.cpp2   intA=0;//Global Initialization Zone3   Char*P1;//Global Uninitialized Zone4 Main ()5   {6    intb; Stack7    Chars[]="ABC";//Stack8    Char*P2;//Stack9    Char*p3="123456";//123456\0 in the constant area, p3 on the stack. Ten    Static intC=0;//Global (Static) initialization zone OneP1 = (Char*) malloc (Ten); AP2 = (Char*) malloc ( -);//areas that are allocated 10 and 20 bytes are in the heap area.  -strcpy (P1,"123456");//123456\0 is placed in a constant area, the compiler may optimize it with the P3 to "123456" as a place.  -}

Ii. theoretical knowledge of heaps and stacks
2.1 How to apply
Stack heap: Automatically assigned by the system. For example, declare a local variable in the function int b; The system automatically opens up space for B in the stack
heap: Requires programmers to apply themselves and indicate size, in C malloc function
such as p1= (char*) malloc ();
using the new operator in C + +
such as p2= (char*) malloc ();
but note that P1, p2 itself is in the stack.
2.2 response of the system after application
heap: As long as the remaining space on 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.
stack: First you should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested 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, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space. Also, 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.
2.3 Application Size Limits
stack: Under Windows, 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 Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. 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.
2.4 Comparison of application efficiency
stack: Automatically allocated by the system, faster. But programmers can't control it.
Heap: Is the memory allocated by new, the general speed is slow, and prone to memory fragmentation, but the most convenient to use.
In addition, under Windows, the best way is to use virtual alloc to allocate memory, he is not in the heap, nor in the stack, but directly in the process of the address space to retain a piece of memory, although the most inconvenient to use. But the speed is fast, also the most flexible.
2.5 storage contents in stacks and stacks
stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that 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.
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 the programmer.
2.6 Comparison of access efficiency
Char s1[]= "AAAAAAAAAAAAAAA";
Char *s2= "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA is assigned at run time;
and BBBBBBBBBBB is determined at compile time;
However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap). For example:
1 #include2 Voidmain ()3 {4    CharA=1;5    Charc[]="1234567890";6    Char*p="1234567890";7A = c[1];8A = p[1];9    return;Ten}

The corresponding assembly code

10:A=C[1];
004010678A4DF1MOVCL,BYTEPTR[EBP-0FH]
0040106A884DFCMOVBYTEPTR[EBP-4],CL
11:A=P[1];
0040106D8B55ECMOVEDX,DWORDPTR[EBP-14H]
004010708A4201MOVAL,BYTEPTR[EDX+1]
004010738845fcmovbyteptr[ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.
2.7 Summary
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

Self-Summary:
char *C1 = "abc"; in fact, first in the literal constant area is allocated a piece of "ABC", then assign an address to the stack on the C1 and point to the address, and then change the constant "ABC" will naturally collapse

However, char c2[] = "abc", actually the place where ABC allocates memory is not the same as the above, can be seen from 41990562293624, is completely two places, inferred 4199056 is in the constant area, and 2293624 is in the stack area
2293628 2293624 2293620 This output shows that the area allocated by three pointers is the stack area and is from high address to low address
2293620 4199056 ABC sees that the compiler will C3 optimize the "ABC" to the constant area

Keep thinking.
Code:

1#include <iostream>2 using namespacestd;3 Main ()4 {5    Char*C1 ="ABC";6    CharC2[] ="ABC";7    Char*C3 = (Char*) malloc (3);8    //*C3 = "abc"//Error9strcpy (C3,"ABC");Tenc3[0] ='g'; Oneprintf"%d%d%s\n",&c1,c1,c1); Aprintf"%d%d%s\n",&c2,c2,c2); -printf"%d%d%s\n",&c3,c3,c3); - GetChar (); the}

Output:

2293628 4199056 ABC
2293624 2293624 ABC
2293620 4012976 GBC


As a comment, the subsequent changes will crash.
Visible strcpy (C3, "ABC"), ABC is assigned in another place, and can be changed, and the reference document above is not necessarily,


Ref:http://blog.sina.com.cn/s/blog_5421dfd20100e3tn.html

C language char[] and char* comparison

Related Article

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.