Rule Definition
Using those functions slow down application. It might be necessary to use them however.
In addition it is recommended to centralize their utilization to:
- use of well-proven memory management primitives that are easier to control, test, etc., when they are grouped in a well-identified component than when they are distributed all over the source code,
- create the opportunity to build a custom memory management layer that will replace all individual small-size system "malloc" by individual small-size custom "malloc" that will rely on a centralized large-size system "malloc"; this would increase performance
Remediation
Use a centralized memory allocation function.
Violation Code Sample
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MY_SIZE 3000000
clock_t start, finish;
struct toto
{ int i, j; };
toto * my_array[MY_SIZE];
toto * first = NULL;
toto * MyMalloc( int i)
{
if (0 == i )
first = (toto *)malloc( sizeof( toto) * MY_SIZE);
return (first+i);
}
int main(int argc, char* argv[])
{
double duration;
/* Standard allocation */
start = clock();
for (int i = 0; i<MY_SIZE; i++)
{ my_array[i] = (toto *)malloc( sizeof( toto)); }
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.5f seconds\n", duration );
/* Optimized allocation */
start = clock();
for (i = 0; i<MY_SIZE; i++)
{ my_array[i] = MyMalloc( i); }
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.5f seconds\n", duration );
return 0;
}
Fixed Code Sample
The output of the sample program is the following:
1.69200 seconds
0.21000 seconds
Related Technologies
C++
Technical Criterion
Efficiency - Memory, Network and Disk Space Management
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.