局部变量,如静态 [英] Local variables like static

查看:63
本文介绍了局部变量,如静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我曾尝试制作一个列表,但是创建新的linkList出了点问题.当我尝试使用"newElement"创建element时,没关系,但是"newElement2"返回相同的内存地址,它在pop调用堆栈后不清除局部变量吗?

Hi,
I had tried to make a list, but there is something wrong with create new linkList . when i tried to use "newElement" to create element , it was ok , but "newElement2" return the same memory address , doesn`t it clean the local variables after pop call-stack?

#include <stdio.h>

struct linkList{
	linkList * prev;
	int number;
	linkList * next;
} ;

linkList * newElement(){
	linkList * temp = new linkList;
	return temp;
}

linkList *  newElement2(){
	linkList temp;
	return &temp;
}

int main(){
	linkList * cur = 0;
	linkList * newLinkList;

	linkList head;
	head.prev = 0;
	head.number = 0;
	head.next = 0;

	cur = &head;
	for(int i = 1 ; i <= 10 ; i++){
		newLinkList = newElement2();//here comes the same memory address

		newLinkList->prev = cur;
		newLinkList->number = i;
		newLinkList->next = 0;

		cur->next = newLinkList;
		cur = newLinkList;	
	}

	cur = &head;

	for(int i = 0 ; i < 10 ; i++ ){
		printf("current dataNumber is %d \n",cur->number);
		cur = cur->next;
	}

	getchar();

	return 0 ;
}

推荐答案



newElement2()函数错误地返回了在堆栈上创建的局部变量.

不,堆栈存储器未清理".从调用堆栈中弹出一个地址时...仅该地址已被删除.您在工作集"中获得了相同的地址,因为您的应用程序执行的工作量不是很大.以这种方式思考……有点像读一本书,总是只读256个单词……您将始终返回同一页面.

最好的祝福,
-David Delaune
Hi,

The newElement2() function is incorrectly returning a local variable that was created on the stack.

No, the stack memory is not ''cleaned''. When an address is popped from the callstack... only the address has been removed. You are getting the same address inside your ''working set'' because your application is not doing much very work... Think of it this way...Its sorta like reading a book and always only-reading 256 words... you will always get back to the same page.

Best Wishes,
-David Delaune


调用函数时,堆栈由C/C ++运行时支持设置.
算法:
Stack is set up by the C/C++ runtime support when your function is called.
Algo:
main()
{
 newElement2();
}
<=>
main()
{
 1. Setup stack for newElement2();
 2. Stack for newElement2 include passed parameter.
 3. Pass control to newElement2
 4. clean up stack for newElement2.
}



因此,除非您在堆中创建变量,否则它将消失.
堆栈设置很多次且频繁,因此清理或清零将非常昂贵.所以不是那样做.



So unless you create variable in heap, it will go away.
Stack gets set up a lot of times and frequently, so it will be very expensive to clean up or zero out. So it is not done like that.


这篇关于局部变量,如静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆