Skip to content

SDL_qsort stack buffer overflow with non-transitive comparison function #10055

@aikawayataro

Description

@aikawayataro

When using SDL_qsort with a non-transitive compare function, it is likely to cause a stack buffer overflow:
(taken from https://discourse.libsdl.org/t/sdl-rand-and-sigsev/52111)

#include <SDL3/SDL.h>

#define array_len 100

static int num_compare(const void *_a, const void *_b)
{
    int a = *((int *) _a);
    int b = *((int *) _b);
    return (a > b); // non-transitive
}

int main(int argc, char *argv[])
{
    int nums[array_len];
    for (int i = 0; i < array_len; i++) {
      nums[i] = (int)SDL_rand();
    }

    SDL_qsort(nums, array_len, sizeof (int), num_compare);

    for (int i = 0; i < array_len; i++) {
      SDL_Log("%i", nums[i]);
    }
    return 0;
}
./a.out
*** stack smashing detected ***: terminated
Aborted (core dumped)

The solution is to update the qsort implementation to https://www.mccaughan.org.uk/software/qsort.c-1.16 , which fixes the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions