if I am allocating memory using malloc,
Second time when I execute the code,I will free the memory.
If not,I want to free the memory allocated in first execution. how to do?
Re: malloc, free
When ever the code execution get complete all the allocated memory will get free.So in the first example the allocated memory freed when the end of the code execution by the OS .
In the second example you have freed the memory before the execution of the code.
Freeing the memory by yourself after the usage will give the way to use the same memory in the further execution of the code.it is highly recommended .
Re: malloc, free
> With the code in example2, whether the memory allocated in first execution (example1)is also free.
I assume this is a question. No, it will not be freed. If you forget the value returned from malloc, your code will leak memory. Not a big deal if it's a small utility that does some stuff then exits, but if it's a program that needs to run indefinitely then eventually it will crash due to lack of memory.
But even if it is just a small utility, you should still free the memory, because small utilities have the habit of growing, or their code being copied/pasted into other projects, and that's where the problem starts. So don't create difficulties for yourself later on.
> If not,I want to free the memory allocated in first execution. how to do?
You have to call free with the value 1000. There's no other way. If you call malloc() and get back the address X, your program MUST call free(X) at some point. It doesn't matter where you store X; you can keep it in "temp", or you can keep it in some other variable, you could even write it to a file and retrieve it from that file when you want to free the memory, but you must call free with the address returned by malloc when you're done with the memory.
Your question implies that you think that temp contains not just 2000 but also 1000 and maybe a list of all values it's ever stored, otherwise how else do you think free(2000) would know to free(1000). Drop this silly idea immediately; a variable stores one value only, and when that value is overwritten with another value it is irretrievably lost forever.
|All times are GMT +5.5. The time now is 04:00.|