Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined elements in struct array

I am creating a client/server application and want to call functions dynamically. i have create the following struct:

typedef struct _cmd cmd;
struct _cmd
{
    const char *name;
    void (*func)(int s,int ac, char **av);
};

When the client send a command to the server the server will browse through an array of commands:

cmd cmds[] = {
        { "CREATE", cmd_create },
        { "EXIT" ,  cmd_exit },
        { "LIST", cmd_list },
        { "READ", cmd_read },
        { "DELETE", cmd_delete },
        { "UPDATE", cmd_update }
};


cmd *find_cmd(const char *name) {
    cmd *c;
    for (c = cmds; c->name; c++) {
        if (stricmp(name, c->name) == 0)
            return c;
    }
    return NULL;
}    

Please not that

stricmp()

is not a typo, it a case-insensitive version of strcmp.

I now the following problem. When I call find_cmd() and pass an invalid commmand, my application crashes. my debugging messages showed the following:

Browsing Command: CREATE
Browsing Command: EXIT
Browsing Command: LIST
Browsing Command: READ
Browsing Command: DELETE
Browsing Command: UPDATE
Browsing Command: �p�
Browsing Command: �(�

After that i get the segfault. This looks to me as if there are some undefined elements in that struct arraym but where do they come from? What am I overlooking? Thanks in advance for any pointers.

like image 995
Fish-Guts Avatar asked Jun 20 '14 17:06

Fish-Guts


1 Answers

You need a "null" element at the end of your list to trigger the c->name (!= NULL) test in your for loop.

Change

cmd cmds[] = {
        { "CREATE", cmd_create },
        { "EXIT" ,  cmd_exit },
        { "LIST", cmd_list },
        { "READ", cmd_read },
        { "DELETE", cmd_delete },
        { "UPDATE", cmd_update }
};

to

cmd cmds[] = {
        { "CREATE", cmd_create },
        { "EXIT" ,  cmd_exit },
        { "LIST", cmd_list },
        { "READ", cmd_read },
        { "DELETE", cmd_delete },
        { "UPDATE", cmd_update },
        { NULL, NULL }
};
like image 197
DoxyLover Avatar answered Oct 07 '22 16:10

DoxyLover