i tried to implement a simple heap sort algorithm, but it always terminates with the message [1] 25535 abort ./build/maps.
I ran lldb ./build/maps core to inspect the error, this is what I got:
stop reason = signal SIGABRT
frame #0: 0x00000001b65219b8 libsystem_kernel.dylib`__pthread_kill + 8
libsystem_kernel.dylib`__pthread_kill:
-> 0x1b65219b8 <+8>: b.lo 0x1b65219d8 ; <+40>
0x1b65219bc <+12>: pacibsp
0x1b65219c0 <+16>: stp x29, x30, [sp, #-0x10]!
0x1b65219c4 <+20>: mov x29, sp
Target 0: (maps) stopped.
i don't know what to do with this. I suspect, that there is somewhere a overflow, because if I call the function with the length of the array - 1 it works. If i run lldb step by step I can't find the error, it just works til the end, what really confuses me However here is my Code:
#include <stdio.h>
#include <stdlib.h>
#include "./collections/heap.h"
int compare(const void *element_1, const void *element_2) {
const int *a = element_1;
const int *b = element_2;
return *a - *b;
}
int main(int argc, char **argv) {
int array[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
heap_sort(array, 9, sizeof(array[0]), compare);
for(int i = 0; i < 9; i++) {
printf("%d\n", array[i]);
}
}
#include "heap.h"
#include "../assert.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
static void percolate(void *, int, size_t, size_t, int (*compare)(const void *, const void *));
static void swap(void * , int, int, size_t);
void heap_sort(void *array, size_t n_elements, size_t size_per_element, int (*compare)(const void *, const void *)) {
int len = n_elements * size_per_element; // array has `len` bytes.
unsigned char *src = array;
for(int i = len/2; i >= 0; i -= size_per_element) {
percolate(array, i, len - size_per_element, size_per_element, compare);
}
printf("successfully ran first for loop\n");
for(int i = len; i > 0; i -= size_per_element) {
swap(array, 0, i, size_per_element);
percolate(array, 0, i - size_per_element, size_per_element, compare);
}
printf("successfully ran second for loop\n");
}
/**
* Swaps the variables at index i and index j.
*/
static void swap(void *array, int i, int j, size_t element_size) {
unsigned char *src = array;
while(element_size-- > 0) {
src[i] ^= src[j];
src[j] ^= src[i];
src[i] ^= src[j];
++i;
++j;
}
}
static void percolate(void *array, int current, size_t last, size_t element_size, int (*compare)(const void *, const void *)) {
unsigned char *src = array;
int i = current;
int j;
while((2*i) + element_size <= last) {
j = (2*i) + element_size;
if(j+ element_size <= last) {
if(compare(&src[j], &src[j+element_size]) > 0) {
j += element_size;
}
}
if(compare(&src[i], &src[j]) > 0) {
swap(array, i, j, element_size);
i = j;
} else {
break;
}
}
}
Thank you