Re: why does this work?
- From: Barry Schwarz <schwarzb@xxxxxxxxx>
- Date: Mon, 27 Mar 2006 21:09:33 -0800
On Mon, 27 Mar 2006 19:01:37 -0800, Matt Kowalczyk
<matt5531@xxxxxxxxxxx> wrote:
Hello,
Can someone explain to me why the following code works correctly? It would seem
like it shouldn't.
If you included the actual code we might be able to.
irc_client.c contains:
#include "ircclient.h
Missing the closing ".
IRCClient* init_irc_client() {
IRCClient* irc_client;
irc_client = malloc(sizeof(IRCClient));
irc_client->irc_connect_to = irc_connect_to;
// return irc_client;
Does you compiler not give a diagnostic?
}
irc_client.h contains:
typedef struct {
/* methods */
int (*irc_connect_to) (xdcc_packet* packet);
Since xdcc_packet is not defined till later, this also must produce a
diagnostic.
} IRCClient;
typedef struct {
char* server;
int port;
char* channel;
char* nick;
int packet_nr;
} xdcc_packet;
My main.c contains:
#include <assert.h>
#include "ircclient.h"
int main(int argc, char* argv[]) {
IRCClient* client;
xdcc_packet packet;
/* packet init code goes here - deleted for clarity */
client = init_irc_client();
At this point you invoke undefined behavior, trying to use the return
value from a function that forgot to return it. The fact that it
appears to work properly is just really bad luck. (I expect the
reason for the apparent success is that the register the value would
have been returned in just happens to have the "correct" value as a
residual side affect of the last statement executed in the function.)
assert(client);
If you delete the assignment above, then client never gets
initialized; its value is indeterminate. Attempting to evaluate an
indeterminate value is more undefined behavior.
client->irc_connect_to(&packet);
free_irc_client(client);
free_xdcc_packet(&packet);
return 0;
}
My question is, init_irc_client() initializes client in the main function
regardless of whether init_irc_client() contains the return statement or not. In
my example code above, I have the return statement commented out, however when I
call client->irc_connect_to, the appropriate function is called. Why is client
getting initialized regardless of the fact that init_irc_client returns a
pointer to a client or not.
Really bad luck, destined to fail only when you demonstrate your
product to an important customer or you submit it for some form of
formal certification. With undefined behavior, good luck is an
immediate software error with a diagnostic that helps you debug the
mistake.
The assert(client) statement _only_ fails if I don't make the assignment:
client = init_irc_client();
Thanks,
Matt
Remove del for email
.
- References:
- why does this work?
- From: Matt Kowalczyk
- why does this work?
- Prev by Date: Re: arrays question
- Next by Date: Re: Why no segmentation fault
- Previous by thread: Re: why does this work?
- Next by thread: design question
- Index(es):
Relevant Pages
|