Click here to Skip to main content
12,819,421 members (34,447 online)
Rate this:
Please Sign up or sign in to vote.
See more: C
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 ;
Posted 29-Dec-11 17:06pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


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
Rate this: bad
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.
 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.

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

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170308.1 | Last Updated 30 Dec 2011
Copyright © CodeProject, 1999-2017
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