For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done?
char *x = malloc(256);
strcpy(x, "Hello World");
// return back unused x memory allocation
For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done?
char *x = malloc(256);
strcpy(x, "Hello World");
// return back unused x memory allocation
You can call realloc
to change the size of an allocation; this can be used to make it bigger or smaller.
The computer would have no basis for automatically making your allocation smaller.
It's not automatically done. That's both, the nice and horrible thing about manual memory management.
You would need to explicitly call free(x);
to release the memory back to the operating system. And it's a pain to keep track of your malloc()
/free()
pairs, but it pays off because you have fine grained control over the memory your program uses.
If you want to allocate just the exact amount of memory, then you should. Normally when you call malloc()
you don't know the allocation size at compile time, so normally you would allocate the exact amount of memory.
If you want a grow/shrink memory buffer you should take into consideration the fact that malloc()
is a expensive call. So you would normally allocate enough — a good estimate of how much you need — memory and then shrink it when you know that it wont grow more, or grow it if you estimated too little.