C + + foundation — pointer — the pit where the stack is removed when the pointer is returned

Time:2021-9-8
1. Function local variable address release pit

Main () calls the test () method to return the address of a, but a is a local variable of test (). Therefore, after the call of test (), the stack space of test () is removed and the storage space of a is released. Even if the pointer to a is saved, 10 cannot be obtained. The reason why 10 can be obtained for the first time is that the compiler optimizes and retains data once.

#include 
using namespace std;
int* test();

int main(){
	int *p = test();
	cout<< *p <

2. Performance of string and char *

From this experiment, it is found that the address of string does not change, and the correct value can be obtained even after the function is executed.

Explanation: the string exists in the static area rather than in the function stack. The way of extinction is different from that of ordinary variables, so its value can still be obtained correctly

​ Char * is the same as the variable in the previous example, but it’s gone.

#include 
#include 

using namespace std;
string test();
char* test1();
int* test2();
int main() {
	string p = test();
	Cout < < address of variable string < < &p < < endl;
	cout << p << endl;
	cout << p << endl;
	char* p1 = test1();
	Printf ("address of variable char array% P \ n", P1);
	Cout < < value of char array < < P1 < < endl;
	Cout < < value of char array < < P1 < < endl;

	/**
	The result is
	Address of variable string in function 0x6ffe00
	Address of variable string 0x6ffe00
	helloworld
	helloworld
	Address of variable char in function 00000000006ffdc0
	Address of variable char array 00000000006ffdc0
	Value of char array  
	Value of char array
	**/
}

string test() {
	string a = "helloworld";
	Cout < < address of variable string in function \ n "< &a < < endl;
	return a;
}


char* test1() {
	char a[] = { 'h','h','h' };
	Printf ("address of char array in function% P \ n", a);
	return a;
}

Storing the above local variables in the heap can be avoided

Recommended Today

Blog Garden Background page dynamic effects

1. To set animation, you must first apply for permission 1.1 first enter [my blog park] and enter [settings] in [management] 1.2 find [blog sidebar announcement] and click [apply for JS permission] 1.3 write the content of application JS permission (examples are as follows) Dear blog administrator: Can you open JS permission for me? I […]