Saturday, 9 December 2017

memory management - Garbage collector in c for variables inside a loop

itemprop="text">

I am mainly a Java person recently
working on some projects involving C so please bear with me if it's a basic C
question.



So inside my main I have a while loop
and I declare a variable each
iteration.



int
main()
{
int done = 0;
while(!done)

{
char input[1024];
scanf("%s", input);
//parse the
input string
...
}
}



Now since the input
variable will change every time depending on what the user wants I have to use a "new"
variable each time. However, I think the above declaration will be causing memory leak
ultimately(or will it?). I would like to know if gcc takes care of garbage
collection.



Is there any better approach without
allocating and freeing after every iteration?


class="post-text" itemprop="text">
class="normal">Answer





I think the
above declaration will be causing memory leak ultimately(or will
it?).




No, it
wouldn't: input is an automatic (AKA
"Stack") variable, it will get "deallocated" as soon as it goes out of scope (i.e. after
the closing brace).





Is there any better approach without allocating and freeing after every
iteration?




There
is no actual allocation or deallocation going on: the space in the automatic memory (AKA
"on the stack") is allocated by some compile-time bookkeeping around the stack pointer.
The access of automatic variables is a very fast operation heavily assisted by hardware,
so there is no loss of efficiency there.



Dynamic
memory allocation (Java-style) is done with
malloc/calloc/realloc
in C. These are not garbage collected - you need to explicitly
free every pointer that you allocated.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...