Click here to Skip to main content
15,921,212 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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; = 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;


	return 0 ;


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
Share this answer
Stack is set up by the C/C++ runtime support when your function is called.
 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.
Share this answer

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

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900