Skip to content

Overflow in cross_merge #10

@SaculRennorb

Description

@SaculRennorb

The source was compiled using MSCV 19.39.33523.

While integrating this library into a new project I might have found an oob in the last loop of cross_merge:

fluxsort/src/quadsort.c

Lines 512 to 515 in 93aac37

while (ptr <= tpr)
{
*ptd++ = *ptr++;
}

called from
FUNC(cross_merge)(swap + half1, array + half1, quad3, quad4, cmp);

With specific, large input arrays (492052 elements in the repro case) this overflows the destination buffer of len(swap) - half1 = 492052 - 246026 = 246026, and by quite a bit I might add:

image

I have a bunch of tests that work perfectly fine, including ones that just try random sequences of numbers, but this specific input fails. It also doesnt seem to ony be a size issue, because other tests with 230k elements work fine. I was not able to reduce the crash input, but maybe something like quickcheck could find a more minimal case.

I purposefully did not use the def'ed version of cmp because the real usecase is more complex.

Unfortunately I do not understand the implementation well enough to point at why this happens, but i will provide the almost 500k inputs for reproduction:

#define FUNC(f) f
#define VAR long long

typedef int CMPFUNC (VAR* a, VAR* b);

#include "sort.c" // this is just quadsort and fluxsort glued together

#include <stdio.h>

int cmp(VAR* a, VAR* b) { return *a - *b; }


int verify(VAR* array, int len)
{
	for(int i = 0; i < len - 1; i++)
	{
		if(cmp(array + i, array + i + 1) > 0) {
			printf("Sorting breaks at index %d (%lld > %lld)", i, array[i], array[i + 1]);
			return 1;
		}
	}

	printf("Everything sorted properly.");
	return 0;
}


long long data[] = {
 // zip input.txt content here ------------------------------------------------------------------------------------
};
int main()
{
	fluxsort(data, sizeof(data) / sizeof(data[0]), cmp);

	return verify(data, sizeof(data) / sizeof(data[0]));
}

Neither pastebin nor gh allow 3.5 meg of text, so i attached the input as a zipped text file. And while I was at it I zipped the whole test project aswell, in case that is of any use.

tests.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions