Skip to content

Misleading documentation or bug in zhash ? #2309

Description

@Mathsoum

Here the documentation that puzzles me :

//  After a successful first/next method, returns the key for the item that
//  was returned. This is a constant string that you may not modify or
//  deallocate, and which lasts as long as the item in the hash. After an
//  unsuccessful first/next, returns NULL.
CZMQ_EXPORT const char *
    zhash_cursor (zhash_t *self);

I understand that zhash_cursor shall return NULL after an unsuccessful zhash_next.
Here's the thing : is the last zhash_next, i.e. the one that returns NULL in an iteration loop, considered unsuccessful ?
I would answer yes. And yet, in this case, zhash_cursor does not return NULL after that last zhash_next, it returns the key from the previous iteration.

Here is a main function that illustrate this behavior

#include "stdlib.h"
#include "stdio.h"
#include "czmq.h"

int main(int argc, char** argv)
{
    zhash_t* h = zhash_new();
    zhash_autofree(h);

    zhash_insert(h, "Key 1", "Value 1");
    zhash_insert(h, "Key 2", "Value 2");
    zhash_insert(h, "Key 3", "Value 3");

    const char* value = zhash_first(h);
    const char* key = zhash_cursor(h);
    printf("%s => %s\n", key, value);

    value = zhash_next(h);
    key = zhash_cursor(h);
    printf("%s => %s\n", key, value);

    value = zhash_next(h);
    key = zhash_cursor(h);
    printf("%s => %s\n", key, value);

    value = zhash_next(h);
    key = zhash_cursor(h);
    printf("%s => %s\n", key ? key : "NULL", value ? value : "NULL");  // Expected to print "NULL => NULL", but prints "Key 1 => NULL" 

    zhash_destroy(&h);
    return EXIT_SUCCESS;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions