How can i release the memory that I used for a variable (e.g. a long string) in C?
Assuming that you allocated the memory dynamically (using malloc
or another memory allocator) you free it using free
. If the memory was statically allocated, you can't free it.
It really depends on how you declare your variable - if it's a regular variable you cant "deallocate" it's memory - it will be released when it gets out of scope like here:
for (int i=0;i<10;i++) {
int k=i;
//do stuff
}
i will be deallocated when you exit the loop and k will be allocated and deallocated on every pass through the body of the loop.
When it's about runtime memory allocation you can use your trusty malloc and free :)
int* intArray;
malloc(200 * sizeof(int));
This will give you an array of 200 ints.
Assuming you aren't using malloc, and are creating a string or buffer using
char array[100];
But you know that you're only using it for a very short part of a long function, you can just place that part of the function in another set of { }
int reallylongfunction() {
// Do a lot of stuff
{
char stringbuffer[100];
// Do stuff with the buffer...
// Ok, we're done with the buffer, and don't want it anymore
}
// Do a lot more stuff
return;
}
This will cause the buffer to go out of scope, and be released. Be careful though, anything else you declare inside the extra { } will go out of scope and disappear as well!
Edit: Damn, comments are right. Static strings going out of scope doesn't do any good. Edited so it's just an array.
I'd suggest you have a look at ustr, which is a string API that you can use with automatic, constant and dynamicly allocated strings ... only two of which you can actually "free", but all of which you can treat the same way and pass to ustr_free().
You might well still want to learn about how the stack, the heap and data (RO text strings) are "allocated" and "freed" ... but using a usable API while you are learning that will stop help you you a lot (and are going to be much faster than what you'd do on your own).
This question really cannot be answered without more information. The only way to know how to free an object (or even know whether or not it should be freed) is to know how the object was allocated.
And when I say object, I mean not just a C++ 'object', but 'object' as is used in the C standard:
region of data storage in the execution environment, the contents of which can represent values