MergeSort algorithm segmentation fault error when a record of one million elements is inserted, up to 300k values sort without problem.
Data Structures are given as input and based on the attempts i’ve tried to make, i think it’s not a memory problem
void merge_sort(void *base, int left, int mid, int right, size_t size, comparator(void *value1, void *value2) {
int len1 = mid - left + 1;
int len2 = right - mid;
char left_array[len1 * size];
char right_array[len2 * size];
char *arr = (char *)base;
for(int i = 0; i < len1; i++){
memcpy(left_array + i * size, arr + (left + i) * size, size);
}
for(int i = 0; i < len2; i++){
memcpy(right_array + i * size, arr + (mid + 1 + i) * size, size);
}
int i, j, k;
i = 0;
j = 0;
k = left;
while(i < len1 && j < len2){
if((compar(left_array + i * size, right_array + j * size) < 0) || (compar(left_array + i * size, right_array + j * size) == 0)){
memcpy(arr + k * size, left_array + i * size, size);
i++;
}else{
memcpy(arr + k * size, right_array + j * size, size);
j++;
}
k++;
}
while (i <= len1) {
memcpy(arr + k * size, left_array + i * size, size);
i++;
k++;
}
while (j < len2) {
memcpy(arr + k * size, right_array + j * size, size);
j++;
k++;
}
}
void merge(void* base, int left, size_t nitems, size_t size, comparator(void *value1, void *value2) {
if(left < nitems){
int mid = left + (nitems - left)/2;
merge(base, left, mid, size, compar);
merge(base, mid + 1, nitems, size, compar);
merge_sort(base, left, mid, nitems-1, size, compar);
}
}
I allocated as much memory as possible but it doesn’t seem to be a memory issue
>Solution :
Quick explanation
char left_array[len1 * size];
char right_array[len2 * size];
On these lines you are allocating about four million bytes (approx. 4Gb) of memory. This memory is allocated on the stack, and the thing about stack is that it can’t grow indefinately, and it has an upper bound. The default stack size on windows is 1Mb, and on linux it’s 2Mb.
The reason for the crash – accessing memory outside of the stack bounds. So if you want to fix the issue, you probably would want to either allocate this memory not on the stack, allocate less memory, or make the stack larger. Since this is obviously a testing code I would assume that making the stack larger is an acceptable solution, though in this case the amounts of memory you’re allocating are so large, that allocating them on heap is probably better.
You can allocate memory on the heap using the malloc function, you can look up the usage online. This is the simplest, and probably the best solution.