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?
No, it wouldn’t:
inputis an automatic (AKA “Stack”) variable, it will get “deallocated” as soon as it goes out of scope (i.e. after the closing brace).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/reallocin C. These are not garbage collected – you need to explicitlyfreeevery pointer that you allocated.