Garbage Collection in C : Local variables question
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Distribution: Solaris 11.4, Oracle Linux, Mint, Debian/WSL
Posts: 9,789
Rep:
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.
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.
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:
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.
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
...
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.
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054
Original Poster
Rep:
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.
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.
Distribution: Slackware 12 Kernel 2.6.24 - probably upgraded by now
Posts: 1,054
Original Poster
Rep:
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.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.