The following two articles are analyzed in detail.
Source http://blog.csdn.net/shiwei0124/archive/2009/11/26/4877546.aspx
String storage and static storage areas, stacks, and stacks
Occasionally, a string problem occurs during programming. It seems that const char * cannot be converted to tchar *, but this error sometimes exists and sometimes does not exist, I have not paid much attention to it. I only know that "ABC" should be of the const type.
I accidentally saw two posts today and finally had a clear understanding of the problem.
Tip 1:
Http://topic.csdn.net/u/20090302/17/900b3797-3642-4569-a623-dc0f8ebd8401.html? Seed = 1325371970
# Include <stdio. h>
Int ()
{
Int test = 10;
Return test;
}
Int main ()
{
Int A = ();
Printf ("% d/n", );
Return 0;
}
The above code can be compiled. I want to ask if the lifetime of the test variable in the () function is not only in the () function? How can I return a successful response?
Why can't the following code be used? What is the difference between the variable lifetime in the two programs?
# Include <stdio. h>
Char * ()
{
Char p [] = "hello world ";
Return p;
}
Int main ()
{
Char * str = NULL;
Str = ();
Printf ("% s", str );
}
The better answer is:
I:
The key here is:
Int a = ();
Actually a = test; and test crashes. We don't care, there is.
While
Str = ();
Str = p.
After that, both p and p point to the heap zone, but str still points to the heap zone that p points.
Do you understand?
II:
Note:
Int ()
{
Int test = 10;
Return test;
}
The returned value is true. After the call, test is released, but its value is returned.
While
Char * ()
{
Char p [] = "hello world ";
Return p;
}
The returned pointer is the pointer value, but the returned pointer value is useless because "hello world" is released.
(The space for storing strings is released. What is the usage of this pointer value ?)
Then read the second post:
Http://topic.csdn.net/u/20091126/10/8e6dfe37-b12f-410f-9e02-83eaad1c30a0.html? 25692
Problem:
First look post http://topic.csdn.net/u/20090302/17/900b3797-3642-4569-a623-dc0f8ebd8401.html? Seed = 1325371970
The answer in this post is profound. Correct. However, some problems occurred during the experiment.
C/C ++ code
Char * FuncC ()
{
Char * a = "hello word ";
Return;
}
Char * FuncB ()
{
Char a [] = "hello word ";
Return;
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
Char * B, * c;
C = FuncC ();
B = FuncB ();
Char a [100];
: Memset (a, NULL, 100 );
Strcpy (a, c );
Std: cout <"A =" <a <"B =" <B <"C =" <c <endl;
Getchar ();
Return 0;
}
Output result:
C/C ++ code
A = hello word B = p _/* (unknown operation) */C = hello word; // I also think the result of C is undefined, but no matter how it is operated, the results are all correct.
The only difference is that in FuncB, the header pointer of the partial pointer array is returned, and in FuncC, a copy of the partial pointer is returned. They determine the size and allocate space during compilation. They all point to string constants. Why FuncB fails. FuncC is successful.
Or, the result is unknown, even if the output is correct ,..
Answer:
I:
I don't know how much I know about stacks, stacks, and static zones,
In FuncC, char * a = "hello word ";
A does not allocate space. Instead, the string "hello word" is placed in the static zone (at the same level as the global variable). In the stack, it is only the pointer a (4-byte pointer ), after the function is returned, only a is destroyed, and the strings in the static zone are not destroyed.
C = FuncC ();
Although a is destroyed, c receives the returned value and still points to the static zone string "hello word"
So there is no problem.
In the opposite FuncB (),
Char a [] = "hello word ";
The entire string is placed in the stack. The function is destroyed when it returns, and the result is unknown.
II:
FuncA returns a pointer pointing to the static data zone, and the function returns a copy of the pointer, it still points to the "hello word" entry in the static data area.
FuncB applies for a data zone in the function stack to store the data. a [] = "hello word"; there is a data copy operation, is to copy the data in the static data zone to the stack data zone. When the function exits, if the system simply rolls back the top pointer of the stack, maybe the data that a points to is still "hello word". If the system first erased all the stack data when the function exits and then rolled back the top pointer of the stack, the data that a points to is unknown.
We can see that char a [] = "sdaf" and char * a = "sdaf" have different mechanisms though they look similar on the surface, the difference is that the string storage method of "sdaf" is different.
The following section describes the static storage areas, stacks, and stacks.
About Dynamic Object creation: Generally, the compiler divides the memory into three parts: static storage area, stack, and heap. The static storage area stores global variables and static variables, stack stores variables and addresses related to call functions, and stack stores dynamically generated variables. In c, it refers to malloc, the free operation generates the released storage space. In c ++, it refers to the storage area used by the new and delete operators.
1. static storage allocation
It refers to the allocation of a fixed storage location for data objects during compilation and remains unchanged during runtime. That is, once a location in the bucket is assigned to a data name, the location (Address) belongs to the data name throughout the running process of the target program.
The data zone generated by the static storage allocation is called the static data zone.
Static storage allocation is applicable to languages that do not allow recursive procedures or recursive calls and do not allow variable volume data structures
Static storage allocation features: simple and easy to implement
For example, in FORTRAN, all its data belongs to this type.
2. Dynamic Storage Allocation
Dynamically allocates storage locations for Data Objects in the source program during the running stage.
Features of languages that implement dynamic storage allocation:
Allow recursive process
Variable data structures (variable arrays or records) are allowed)
Allow users to freely apply for and release space
This type of program cannot determine the size of the data space required during the runtime during compilation. It must be dynamically determined when the program is running.
There are two dynamic storage allocation methods: stack and heap ).
3. stack-based Dynamic Storage Allocation
Open up a stack zone in the data space. Whenever a process is called, the data space required by the stack is allocated at the top of the stack, and the space is released at the end of the process. The use of the space must follow the principle of first lending and then returning.
Features: simple management and high space efficiency
Stack-based dynamic storage allocation is suitable for typical procedural languages such as PASCAL and C.
4. heap dynamic storage allocation
A continuous storage area (usually called a heap) is opened in a data space. A block is borrowed from this space whenever necessary and is returned if not used. Borrowing and returning do not necessarily follow the principle of "lending first and then returning.
Heap dynamic storage allocation is suitable for languages where users can freely apply for and return data spaces, such as C ++.
Features: wide range of applications, prone to fragmentation.
How to make full use of space is a challenge.
This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/shiwei0124/archive/2009/11/26/4877546.aspx
Source http://hi.baidu.com/%D0%C7%BB%F0%D3%C4%C0%B6/blog/item/410174384e529ffbb211c71c.html
Why is a constant string in a static storage zone?
Char * c = "chenxi ";
The book says: "chenxi" is treated as a constant and placed in the static memory zone of the program.
The general int I = 1;
1 is also a constant. Why is 1 not placed in the static memory zone of this program?
Please kindly advise!
All character escape constants are placed in the static memory area.
Because string constants rarely need to be modified, putting them in the static memory area will improve efficiency.
Example:
Char str1 [] = "abc ";
Char str2 [] = "abc ";
Const char str3 [] = "abc ";
Const char str4 [] = "abc ";
Const char * str5 = "abc ";
Const char * str6 = "abc ";
Char * str7 = "abc ";
Char * str8 = "abc ";
Cout <(str1 = str2) <endl;
Cout <(str3 = str4) <endl;
Cout <(str5 = str6) <endl;
Cout <(str7 = str8) <endl;
Result: 0 0 1 1
Str1, str2, str3, and str4 are array variables which have their own memory space;
Str5, str6, str7, and str8 are pointers pointing to the same constant area.
Problem introduction:
Let's take a look at the output of the following program:
# Include <stdio. h>
Char * returnStr ()
{
Char * p = "hello world! ";
Return p;
}
Int main ()
{
Char * str = NULL; // Initialization is required.
Str = returnStr ();
Printf ("% s/n", str );
Return 0;
}
There is no problem with this, because "hello world! "Is a String constant stored in the static data area,
Assign the first address of the static data area where the String constant is stored to the pointer,
Therefore, when the returnStr function exits, the memory where the String constant is located will not be recycled, so it can be smoothly accessed through the pointer.
However, the following issues occur:
# Include <stdio. h>
Char * returnStr ()
{
Char p [] = "hello world! ";
Return p;
}
Int main ()
{
Char * str = NULL; // Initialization is required.
Str = returnStr ();
Printf ("% s/n", str );
Return 0;
}
"Hello world! "Is a String constant stored in the static data area. That's right,
However, a String constant is assigned to a local variable (char [] array), which is stored in the stack,
In this way, there are two pieces of memory with the same content, that is, "char p [] =" hello world! ";" This statement makes "hello world !" This string has two copies in the memory, one in the dynamically allocated stack and the other in the static storage area. This is the most essential difference from the former,
When the returnStr function exits, the stack needs to be cleared, and the memory of local variables is also cleared,
Therefore, the function returns a released memory address, so garbled characters are printed.
If the return value of a function is not the address of a local variable, the local variable must be declared as static. As follows:
# Include <stdio. h>
Char * returnStr ()
{
Static char p [] = "hello world! ";
Return p;
}
Int main ()
{
Char * str = NULL;
Str = returnStr ();
Printf ("% s/n", str );
Return 0;
}
This problem can be better explained through the following example:
# Include <stdio. h>
// The returned address is the address of the local variable, which is located in the dynamic data zone and in the stack.
Char * s1 ()
{
Char * p1 = "qqq"; // to test 'Char p [] = "Hello world! "'Is there a copy of the string in the static storage area?
Char p [] = "Hello world! ";
Char * p2 = "w"; // to test 'Char p [] = "Hello world! "'Is there a copy of the string in the static storage area?
Printf ("in s1 p = % p/n", p );
Printf ("in s1 p1 = % p/n", p1 );
Printf ("in s1: string's address: % p/n", & ("Hello world! "));
Printf ("in s1 p2 = % p/n", p2 );
Return p;
}
// Return the address of the String constant, which is located in the static data zone.
Char * s2 ()
{
Char * q = "Hello world! ";
Printf ("in s2 q = % p/n", q );
Printf ("in s2: string's address: % p/n", & ("Hello world! "));
Return q;
}
// The address of the static local variable is returned. The address is located in the static data zone.
Char * s3 ()
{
Static char r [] = "Hello world! ";
Printf ("in s3 r = % p/n", r );
Printf ("in s3: string's address: % p/n", & ("Hello world! "));
Return r;
}
Int main ()
{
Char * t1, * t2, * t3;
T1 = s1 ();
T2 = s2 ();
T3 = s3 ();
Printf ("in main :");
Printf ("p = % p, q = % p, r = % p/n", t1, t2, t3 );
Printf ("% s/n", t1 );
Printf ("% s/n", t2 );
Printf ("% s/n", t3 );
Return 0;
}
Output result:
In s1 p = 0013FF0C
In s1 p1 = 00431084
In s1: string's address: 00431074
In s1 p2 = 00431070
In S2. q = 00431074
In s2: string's address: 00431074
In s3 r = 00434DC0
In S3: String's address: 00431074
In Main: P = 0013ff0c, q = 00431074, r = 00434dc0
$
Hello world!
Hello world!
This result proves the above explanation. At the same time, we can draw a conclusion:
A String constant is called a constant because it can be regarded as an unnamed string and is a constant and stored in the static data zone.
The static data zone mentioned here is relative to the dynamic data zone such as heap and stack.
The static data area stores global and static variables. In this regard, string constants can also be called an unknown static variable,
Because "Hello world! "This string is referenced in functions S1 and S2, but there is only one copy in the memory, which is similar to static variables.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/yangdelong/archive/2010/04/03/5447362.aspx
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/jdr826857029/archive/2010/10/10/5931106.aspx