C Programming: malloc and free within a loop

c, free, malloc

Solution

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);

Problem

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.

Original source