I just started out with C and have very little knowledge about performance issues with malloc()
and free()
. My question is this: if I were to call malloc()
followed by free()
inside a while
loop that loops for, say, 20 iterations, would it run slower compared to calling free()
outside the loop?
I am actually using the first method to allocate memory to a buffer, read a variable-length string from a file, perform some string operations, and then clear the buffer after every iteration. If my method results in a lot of overhead then I'd like to ask for a better way for me to achieve the same results.
malloc() another example(with for loop)The malloc function allocate a block of memory of specified size and returns a pointer of type void. The free function is used to deallocate the allocated memory.
We have seen that an infinite loop of malloc can create a denial of service by freezing the computer.
In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc .
Definitely slower. (But remember you need to balance the number of malloc
and free
otherwise you get a memory leak.)
If the length varies, you can use realloc
to expand the buffer size.
void* v = malloc(1024);
size_t bufsize = 1024;
while(cond) {
size_t reqbufsize = get_length();
if (reqbufsize > bufsize) {
bufsize = reqbufsize * 2;
v = realloc(v, bufsize);
}
// you may shrink it also.
do_something_with_buffer(v);
}
free(v);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With