STD C quicksort中的可能错误。我想念什么吗?

时间:2018-12-17 19:03:29

标签: c

xorshift初始化:7731

A:  2064221648  1036493097   633233112   583013546   721278080 -1646392714  -829660162   478401127

E:   583013546   633233112   721278080  1036493097  2064221648 -1646392714  -829660162   478401127

预期: -1646392714 -829660162 478401127 583013546 633233112 721278080 1036493097 2064221648

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define debug (0 || (sz < 50))

int cmpfunc(const void* a, const void* b)
{
    int x = *(int*)a;
    int y = *(int*)b;
    return x-y;
}

unsigned int xorshift32(unsigned int x)
{
    /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    return x;
}

int
main()
{
    #define sz 8

    int* a = (int*)malloc(4*sz);

    srand(time(NULL));
    unsigned int init = rand();   printf("xorshift init: %lld\n",init);

    int z=0;
    for(int i = sz-1; i>=0;i+=0)
    {
        a[z] = xorshift32(init) % 0xD0000000U; init = a[z];

        z++;
        i--;
    }
    if(debug)
    {
        printf("A:\n");
        for(int i = 0; i<sz;i++)
        {
            printf("%11d\n", a[i]);
        }printf("\n");
    }

    qsort(a,sz,4,cmpfunc);

    printf("E: \n");
    if(debug)
    {
        for(int i = 0; i<sz;i++)
        {
            printf("%11d\n", a[i]);
        }printf("\n");
    }
}

win7_x64 | gcc.exe(x86_64-posix-seh-rev0,由MinGW-W64项目构建)8.1.0

不使用优化或其他类型的标志。

1 个答案:

答案 0 :(得分:3)

编译为

gcc sort.c -Wall -Wextra

关于不匹配转换说明符存在一个错误(unsigned int需要%u,但是您有%lld-可能是%11d的错字,但即使这样也是错误的。

运行时,我有时得到正确的输出,有时却没有。所以我用-fsanitize=undefined

进行了编译
sort.c:11:13: runtime error: signed integer overflow: 
    1288106901 - -1003011281 cannot be represented in type 'int'
E: 
  290879035
  591885416
  767444883
 1288106901
 1955087149
-1509681722
-1289472872
-1003011281

即您的智能代码在那儿不太聪明。从比较函数返回值的正确方法是

return x < y ? -1 : x > y ? 1 : 0;

return (x > y) - (x < y);

suggested by HolyBlackCat