Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C
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 ;
}
Posted 29-Dec-11 17:06pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 450
1 OriginalGriff 220
2 DamithSL 130
3 Dave Kreskowiak 120
4 Suvendu Shekhar Giri 110
0 OriginalGriff 7,645
1 DamithSL 5,614
2 Sergey Alexandrovich Kryukov 5,344
3 Maciej Los 4,961
4 Kornfeld Eliyahu Peter 4,539


Advertise | Privacy | Mobile
Web03 | 2.8.141223.1 | Last Updated 30 Dec 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100