Suspect that segmentation fault on large arrays occurs because the
list1[]
andlist2[]
ran out of space. With the recursive calls, code is heavily using the stack space. Usemalloc()
andfree()
for large arrays instead of VLA[]Memory allocation could be reduced. Via recursion, this takes > 2n (maybe 4n) memory space. At worst At worst it should be 2n. At a minimum, allocate, populate and sort
list1[]
, then do the same forlist2[]2n
.Use
size_t
rather thanint
for a integer type that can handle all array indexes.// void mergesort (int* list, int len) void mergesort (int* list, size_t len)
Cope with 0 length.
// if(len == 1) return; if(len <= 1) return;