Xlib search window by his name

Hello,
I just try to get the control of a Window by searching his name. I curretly do that :

Window CMD::window_from_name_search(Display *display, Window current, char const *needle)
{
    Window retval, root, parent, *children;
    unsigned children_count;
    char *name = NULL;

    /* Check if this window has the name we seek */
    if(XFetchName(display, current, &name) > 0) {
        int r = strcmp(needle, name);
        XFree(name);
        if(r == 0) {
            return current;
        }
    }

    retval = 0;

    /* If it does not: check all subwindows recursively. */
    if(0 != XQueryTree(display, current, &root, &parent, &children, &children_count)) {
        unsigned i;
        for(i = 0; i < children_count; ++i) {
            Window win = window_from_name_search(display, children, needle);

            if(win != 0) {
                    retval = win;
                break;
            }
        }
        XFree(children);
    }
    return retval;
}

void CMD::window_from_name(char const *name)
{
    m_display = XOpenDisplay(NULL);
    m_root_win = XDefaultRootWindow(m_display);
    m_screen = DefaultScreenOfDisplay(m_display);
    m_window_terminal = window_from_name_search(m_display, m_root_win, name);
}

That previous code should let me play with the window, no ?
But I get an error, a bad window value. I don't Know why. Ps: I'm closing the connection with the X server in the destructor of my class CMD, and I think the problem is here.
Thanks for helping.

EDIT: After some search the m_window_terminal is set to NULL if I don't add a std::cout << "" << std::endl; in the previous function. WHY ?