lfind给出不一致的结果

时间:2015-09-25 12:41:11

标签: c

我试图使用struct的第一个元素作为关键字来搜索大量的结构。因为数组是排序的,bsearch很好,适合我。然后我尝试使用lfind来仔细检查结果,但它给了我一些奇怪的输出。代码如下,当键与数组中的第二个元素匹配时,应该全部命中正确的输出。 bsearch产生了正确的结果,但lfind给出了混合的命中和未命中。在未命中时,似乎lfind甚至没有调用我的比较函数,这表明在lfind中发生了某种错误。我尝试使用lldb进入lfind,但它显示了我无法理解的汇编代码。如果我在调用lfind之前重置void * hit = NULL,它似乎解决了问题。但为什么?机器是MAC OS X Yosemite。

typedef struct SKU{
    char *sku;
    char *desc;
} SKU;

int SKUcmp(const void *, const void *);
int find_desc(const void *, const void *);

int main(int argc, char **argv){
    SKU skus[] = {
        {"", "080686002123"},                  
        {"000020", "Oyster Bay Pinot Gris"},         
        {"000122", "Woodstock Honey 12X250ml Cans"}, 
        {"000238", "Entertainers Cocktail Set"},     
        {"000987", "Hennessy VSOP 750ml"},           
        {"000988", "V Drink 355ML Cans"},            
        {"000989", "Dark Horse 7% 4x6x250ML Cans"}  
    };

    SKU dummy = {"000122", ""};
    void *hit;
    printf("binary search ... ");
    hit = bsearch(&dummy, skus, 7, sizeof(SKU), &find_desc); 
    if(hit) printf("HIT\n");
    else printf("MISS\n");

    // hit = NULL; // seemed to solve the problem
    int x = 7;
    printf("linear search ... ");
    hit = lfind(&dummy, skus, (size_t *)&x, sizeof(SKU), &find_desc); 
    if(hit) printf("HIT\n");
    else printf("MISS\n"); 
}

int find_desc(const void *key, const void *s){
    //printf("entering compare func ...\n");
    char *temp2 = ((SKU *)s)->sku;
    char *temp1 = ((SKU *)key)->sku;

    int result = strcmp(((SKU *)key)->sku, ((SKU *)s)->sku);

    return result;
}

运行x10会产生以下输出:

binary search ... HIT
linear search ... MISS
binary search ... HIT
linear search ... HIT
binary search ... HIT
linear search ... MISS
binary search ... HIT
linear search ... MISS
binary search ... HIT
linear search ... HIT
binary search ... HIT
linear search ... MISS
binary search ... HIT
linear search ... HIT
binary search ... HIT
linear search ... HIT
binary search ... HIT
linear search ... HIT
binary search ... HIT
linear search ... MISS

1 个答案:

答案 0 :(得分:0)

在OS X上sizeof(int) == 4sizeof(size_t) == 8。 将(int*)投射到(size_t*)是一个错误。

可能设置hit = NULL清除堆栈上的字节,这些字节在转换(size_t*)后也用作数组大小。因此,它改变了应用程序的行为。

但是,x的类型应为size_t

size_t x = 7;