0

I am using merge sort function and it contains two list using malloc function. In order to increase the performance, I need to replace the two malloc calls by allocating a single buffer and setting list1 and list2 by pointing into that buffer. This reduces the number of calls to malloc/free to half.

intType* list1 = (intType*)malloc(n1*sizeof(intType));
intType* list2 = (intType*)malloc(n2*sizeof(intType));

where n1 = N /2; and n2 = N -2;

N is the number of elements to be sorted.

I tried different methods but no luck with the implementation. Can someone help here please ?

MikeCAT
  • 73,922
  • 11
  • 45
  • 70

1 Answers1

2

You can do that like this:

/* allocate buffer for the two arrays */
intType* list1 = malloc((n1 + n2) * sizeof(intType));
/* assign pointer with offset */
intType* list2 = list1 + n1;

/* some works */

free(list1);

Also note that casting results of malloc() family is considered as a bad practice.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 1
    Small note that this only works this easily if both types are the same. If 2 lists would have different alignment requirements, then extra padding may have to be added to make sure second list is correctly aligned. – user694733 Apr 26 '21 at 12:19