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.
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 }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With