Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: malloc and free within a loop

Tags:

c

malloc

free

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.

like image 366
kwong Avatar asked Mar 17 '10 16:03

kwong


People also ask

Can I use malloc in a loop?

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.

What happens if I malloc in a loop?

We have seen that an infinite loop of malloc can create a denial of service by freezing the computer.

How does free and malloc work in C?

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.

Can you malloc after freeing?

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 .


1 Answers

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);
like image 124
kennytm Avatar answered Sep 23 '22 01:09

kennytm