Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How bad it is to keep calling malloc() and free()?

Tags:

I'm sending a text file - client-server breakup the text into packets each of 512 bytes but some packets contain text less than max size so on the servers side when receiving each packet I'm calling malloc() to build a string again , is this a bad practice ? is it better to keep a working buffer that can fit for max length and keep iterating , copying and overwriting its values ?

okay @n.m. here is the code , this if is inside a for(;;) loop wakened by the select()

if(nbytes==2) {             packet_size=unpack_short(short_buf);             printf("packet size is %d\n",packet_size);             receive_packet(i,packet_size,&buffer);             printf("packet=%s\n",buffer);             free(buffer); } //and here is receive_packet() function  int receive_packet(int fd,int p_len,char **string) {  *string = (char *)malloc(p_len-2); // 2 bytes for saving the length      char *i=*string;     int temp;  int total=0;  int remaining=p_len-2;  while(remaining>0) {      //printf("remaining=%d\n",remaining);      temp = recv(fd,*string,remaining,0);      total+=temp;      remaining=(p_len-2)-total;      (*string) += temp;  }  *string=i;  return 0;  } 
like image 963
cap10ibrahim Avatar asked Sep 30 '11 15:09

cap10ibrahim


People also ask

What will happen if you keep using malloc () but never free ()?

If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).

What will happen if you malloc and free instead of delete?

If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete. Now, in order to check what happens if we do the reverse, I wrote a small code.

Why you shouldn't use malloc?

There are a number of reasons why malloc() is not generally recommended for embedded applications: The function is commonly not re-entrant (thread friendly), so using it with a real-time operating system may be challenging.

What happens if you free unallocated memory?

Before freeing a pointer, the programmer should make sure that the pointer was previously allocated on the heap and that the memory belongs to the programmer. Freeing an unallocated pointer will cause undefined behavior in the program.


2 Answers

In your example, your function already contains a syscall, so the relative cost of malloc/free will be virtually unmeasurable. On my system, a malloc/free "round trip" averages about 300 cycles, and the cheapest syscalls (getting the current time, pid, etc.) cost at least 2500 cycles. Expect recv to easily cost 10 times that much, in which case the cost of allocating/freeing memory will be at most about 1% of the total cost of this operation.

Of course exact timings will vary, but the rough orders of magnitude should be fairly invariant across systems. I would not even begin to consider removing malloc/free as an optimization except in functions that are purely user-space. Where it's probably actually more valuable to go without dynamic allocation is in operations that should not have failure cases - here the value is that you simplify and harden you code by not having to worry about what to do when malloc fails.

like image 76
R.. GitHub STOP HELPING ICE Avatar answered Nov 06 '22 06:11

R.. GitHub STOP HELPING ICE


There is overhead associated with calling malloc and free. A block has to be allocated from the heap and marked as in use, when you free the revese happens. Not knowing what OS or complier you are using, this could be in the c library or at the OS memory managment level. Since you are doing a lot of mallocs and frees you could wind up severly fragmenting your heap where you may not have enough contiguous free memory to do a malloc elsewhere. If you can allocate just one buffer and keep reusing it, that is generally going to be faster and have less danger of heap fragmentation.

like image 36
user957902 Avatar answered Nov 06 '22 06:11

user957902