Tuesday, 15 July 2014

c - qsort unexpectedly working while using "a > b" as comparator -



c - qsort unexpectedly working while using "a > b" as comparator -

i came across qsort comparator function incorrectly using "a > b" comparing operation. expect code randomly reorder array, working on school's instructional servers (ubuntu 12.04.4 lts). didn't work on own laptop expected, i'm not sure causing bug.

#include <cstdio> #include <cstdlib> void print_arr(int* arr, size_t n) { (int = 0; < n; i++) printf("%d ", arr[i]); printf("\n"); } int int_compar(const void *x, const void *y) { int i_x = *((int*)x); int i_y = *((int*)y); homecoming i_x > i_y; } int main(int argc, char *argv[]) { int n = (1<<4); int in[n]; for(int = 0; < n; i++) in[i] = rand() % 100; printf("before: "); print_arr(in, n); qsort(in, n, sizeof(int), int_compar); printf("after: "); print_arr(in, n); homecoming 0; }

my laptop:

$ ./qsort_test before: 7 49 73 58 30 72 44 78 23 9 40 65 92 42 87 3 after: 23 7 9 3 58 44 42 40 49 30 65 72 73 78 87 92

ubuntu:

$ ./qsort_test before: 83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 after: 15 21 26 27 35 49 59 62 63 77 83 86 86 90 92 93

you breaking contract using qsort, invoking undefined behavior. specifically, comparison-function bad:

7.22.5.2 qsort function

synopsis

#include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

description 2 qsort function sorts array of nmemb objects, initial element of pointed base. size of each object specified size. 3 contents of array sorted ascending order according comparing function pointed compar, called 2 arguments point objects beingness compared. the function shall homecoming integer less than, equal to, or greater 0 if first argument considered respectively less than, equal to, or greater second. 4 if 2 elements compare equal, order in resulting sorted array unspecified. returns 5 qsort function returns no value.

it should more along lines of:

int int_compar(const void *x, const void *y) { int i_x = *(int*)x; int i_y = *(int*)y; homecoming i_x > i_y - i_x < i_y; }

now, comparison-function partially functional instead of broken, does indicate whether first bigger second, does not differentiate between them beingness equal or sec beingness bigger. depending on how algorithm happens written, might create algorithm see equal, not react error @ all, or funny. example, c++ standard-library sorting algorithms written utilize less-than comparison.

c std qsort

No comments:

Post a Comment