LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-03-2006, 01:42 AM   #1
duryodhan
Senior Member
 
Registered: Oct 2006
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054

Rep: Reputation: 46
Garbage Collection in C : Local variables question


Will this work? :

Node* createNode(){
Node a;
return &a;
}

Now I knw I shud do malloc. What I want to ask is .. why will a be deleted ? There is still a variable pointing to it! so where is the problem?
 
Old 12-03-2006, 03:48 AM   #2
jlliagre
Moderator
 
Registered: Feb 2004
Location: Outside Paris
Distribution: Solaris 11.4, Oracle Linux, Mint, Debian/WSL
Posts: 9,789

Rep: Reputation: 492Reputation: 492Reputation: 492Reputation: 492Reputation: 492
This won't work, and will probably trigger a crash sooner or later.
The a variable is stored on the createNode stack, which exists only during this function call livespan.
 
Old 12-03-2006, 06:01 AM   #3
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: Debian
Posts: 2,536

Rep: Reputation: 111Reputation: 111
Quote:
What I want to ask is .. why will a be deleted ?
That's simply by the definition of local variables.
 
Old 12-03-2006, 06:10 AM   #4
BiThian
Member
 
Registered: Aug 2006
Location: Romania
Distribution: NetBSD 3.1
Posts: 118

Rep: Reputation: 15
Because a is an auto variable(with local scope), that's why.
 
Old 12-03-2006, 10:41 AM   #5
jim mcnamara
Member
 
Registered: May 2002
Posts: 964

Rep: Reputation: 36
What is being said: the memory where the stack for createNode currently lives will be overwritten later on by another function call. When createNode executes a return, it loses any rights to memory it had on the stack. The memory used for the "a" variable (it is on the stack because it is a local variable) therefore is free game after the return statment. If the pointer actually works after the createNode function exits it is pure luck. Not good programming.

Last edited by jim mcnamara; 12-03-2006 at 10:43 AM.
 
Old 12-03-2006, 01:41 PM   #6
BiThian
Member
 
Registered: Aug 2006
Location: Romania
Distribution: NetBSD 3.1
Posts: 118

Rep: Reputation: 15
@jim mcnamara: A static variable with local scope is still on the stack?
 
Old 12-03-2006, 03:09 PM   #7
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
BiThian -

If the variable "Node a" were declared "static", it would not be on the stack. But it would still be wrong, because each call to "createNode()" would access the SAME physical node (presumably overwriting any previous value).

duryodhan -

Yes, you need malloc. Specifically, something like:
Code:
  Node *a = malloc (sizeof (struct node));
  return a;
You need to declare "a" a pointer to Node (not a Node).

And you also (of course!) need to take responsibility for deleting ("free()") the Node when you're done.

All local variables declared on the stack ("auto variables") essentially "don't exist" before the subroutine is called, and essentially "don't exist" any more after the subroutine exits.

Does that answer your question?

PS:
Of course, if this were C++ you'd probably use "new" and "delete", and probably manage this in a constructor and a corresponding destructor...

PPS:
duryodhan -

With regard to this (and a couple of your previous posts):Your curiousity is laudible. I appreciate where you're coming from.

But trying to understand 'C' programming with experiments like this is very much like starting your car, opening the hood, closing your eyes ... and sticking your hand randomly into the engine compartment to see what happens.

It's not really a good way to understand how motors run; nor are these questions necessarily good ways to understand how C/C++ programming works.

IMHO .. PSM

Last edited by paulsm4; 12-03-2006 at 03:22 PM.
 
Old 12-03-2006, 03:59 PM   #8
randyding
Member
 
Registered: May 2004
Posts: 552

Rep: Reputation: 31
Variables declared globally, or inside functions as static, are placed in the data segment just the same. The only difference is the local one has more limited scope at compile time. At run time they both have a fixed address that can be referenced inside or outside the function at any time. Here's an example that shows both global and local static variables have fixed addresses in the data segment. Functionally at run time there is no difference between the two variables and their global behavior.
Code:
//usr/bin/gcc -O2 -Wall -o t t.c; ./t; exit 0
#include <stdio.h>
#include <stdlib.h>
char globalstring[]="I'm a global variable.";
char *test(void) {
    static char localstring[]="I'm a local static variable.";
    return localstring;
}
int main() {
    char *p;

    p=test();
    printf("%lx: %s\n%lx: %s\n",(unsigned long)p,p,(unsigned long)globalstring,globalstring);
    return 0;
}
./t
80495b3: I'm a local static variable.
804959c: I'm a global variable.
$ nm t
...
0804959c D globalstring
080495b3 d localstring.0
...
 
Old 12-03-2006, 11:44 PM   #9
BiThian
Member
 
Registered: Aug 2006
Location: Romania
Distribution: NetBSD 3.1
Posts: 118

Rep: Reputation: 15
Quote:
If the variable "Node a" were declared "static", it would not be on the stack. But it would still be wrong, because each call to "createNode()" would access the SAME physical node (presumably overwriting any previous value).
I just wanted to show that the main reason for which the duryodhan's program won't work is that a is an auto variable, not just a local one. That's all.
 
Old 12-04-2006, 01:30 AM   #10
duryodhan
Senior Member
 
Registered: Oct 2006
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054

Original Poster
Rep: Reputation: 46
So what I realize is this :
because the Node a was created with auto, it is created in Stack and not in heap (as with malloc), it will be deleted alongwith the function when the function returns.

But if I did "static Node a" then the variable would be declared in heap, so the variable won't be deleted on returnin from function. Is that right? So instead of malloc I could do "static Node a;" ?

I think I was gettin confused between Java's auto garbage collection and C.

PS: paulsm4
Aw, comeon man!, its fun
ok this is just for fun ... I haven't started with something like Qt (or basically anything that allows me to make a good app). Just the basic functionalities of C,C++,Java are known to me. So thats the questions I asked. And I really like such codes. Agreed mine are really poor , but something like the Quake Invert Square function is just so cool. IMHO.
 
Old 12-04-2006, 03:25 AM   #11
Flesym
Member
 
Registered: Aug 2005
Location: Germany
Distribution: Ubuntu, Debian
Posts: 189

Rep: Reputation: 31
Quote:
Originally Posted by duryodhan
But if I did "static Node a" then the variable would be declared in heap
No, as others already said, static variables are not stored on the heap! Ok, maybe this clarifies things a bit more: Here is a short overview of the different memory parts of a program and wich data are stored in them:

1. Text Segment:
Contains the executable instructions of the program. This section is (usually) write-protected after the program start.

2. The Stack:
Here are all local variables (as well as function parameters and return values) allocated, that are not defined as "static".

3. The Heap:
Every data you dynamically allocate memory for (using malloc & sons) will go here.

4. Data Segment:
Usually contains global variables as well as static ones (regardless if global or local), that are initialized with non-zero.

5. BSS
Usually contains zero-initialized global and static data.


If you want to learn more about how these memory segments are managed, then I'm sure, that google or wikipedia will help you out.
 
Old 12-04-2006, 03:52 AM   #12
duryodhan
Senior Member
 
Registered: Oct 2006
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054

Original Poster
Rep: Reputation: 46
sry for using the word heap.
basically what I wanted to say was that variables declared with static dont get screwed after the end of the function. So doing "static node a " will work. Reading above post it seems like it.
 
Old 12-04-2006, 04:05 AM   #13
BiThian
Member
 
Registered: Aug 2006
Location: Romania
Distribution: NetBSD 3.1
Posts: 118

Rep: Reputation: 15
Declaring a as a static variable will keep a in memory as long as program runs(it won't be "deleted"), but in your case you could meet this problem:
Quote:
But it would still be wrong, because each call to "createNode()" would access the SAME physical node (presumably overwriting any previous value).
 
Old 12-04-2006, 07:16 AM   #14
duryodhan
Senior Member
 
Registered: Oct 2006
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054

Original Poster
Rep: Reputation: 46
ohhh yeah ok. I guess malloc is the only way to go

Thanks all

Last edited by duryodhan; 12-04-2006 at 07:18 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
variables question manicman Linux - Newbie 2 01-21-2006 03:48 PM
Question about variables setianusa Programming 3 05-05-2005 06:38 PM
Using DDD to watch Args and Local Variables jonty_11 Programming 3 03-15-2005 12:01 PM
Local vs Global variables wujee Programming 1 03-11-2005 11:43 PM
Question about php variables lostboy Programming 5 08-07-2003 07:38 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:53 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration