I'm designing a protocol (in C) to implement the layered OSI network structure, using cnet (http://www.csse.uwa.edu.au/cnet/). I'm getting a SIGSEGV error at runtime, however cnet compiles my source code files itself (I can't compile it through gcc) so I can't easily use any debugging tools such as gdb to find the error.
Here's the structures used, and the code in question:
typedef struct {
char *data;
} DATA;
typedef struct {
CnetAddr src_addr;
CnetAddr dest_addr;
PACKET_TYPE type;
DATA data;
} Packet;
typedef struct {
int length;
int checksum;
Packet datagram;
} Frame;
static void keyboard(CnetEvent ev, CnetTimerID timer, CnetData data)
{
char line[80];
int length;
length = sizeof(line);
CHECK(CNET_read_keyboard((void *)line, (unsigned int *)&length)); // Reads input from keyboard
if(length > 1)
{ /* not just a blank line */
printf("\tsending %d bytes - \"%s\"\n", length, line);
application_downto_transport(1, line, &length);
}
}
void application_downto_transport(int link, char *msg, int *length)
{
transport_downto_network(link, msg, length);
}
void transport_downto_network(int link, char *msg, int *length)
{
Packet *p;
DATA *d;
p = (Packet *)malloc(sizeof(Packet));
d = (DATA *)malloc(sizeof(DATA));
d->data = msg;
p->data = *d;
network_downto_datalink(link, (void *)p, length);
}
void network_downto_datalink(int link, Packet *p, int *length)
{
Frame *f;
// Encapsulate datagram and checksum into a Frame.
f = (Frame *)malloc(sizeof(Frame));
f->checksum = CNET_crc32((unsigned char *)(p->data).data, *length); // Generate 32-bit CRC for the data.
f->datagram = *p;
f->length = sizeof(f);
//Pass Frame to the CNET physical layer to send Frame to the require link.
CHECK(CNET_write开发者_如何学Go_physical(link, (void *)f, (size_t *)f->length));
free(p->data);
free(p);
free(f);
}
I managed to find that the line: CHECK(CNET_write_physical(link, (void *)f, (size_t *)f->length)); is causing the segfault but I can't work out why. Any help is greatly appreciated.
I think is the third parameter. Try this:
CHECK(CNET_write_physical(link, (void *)f, (size_t *)(&f->length)));
In this line, I assume third parameter expects a pointer, because you are casting a value to a (size_t *)
. But the value you are casting is a simple integer value. So, whenever the function dereferences the address contained in that value, is when you probably get a SIGSEGV.
With the code I suggested, you are casting a pointer (&f->length)
. So you should be good to go, assuming the function is effectively expecting a pointer to a variable holding a size.
I see two problems here - sizeof(f)
gives you size of a pointer not the Frame
, then you assign size_t
-typed value to f->length
, but later cast it to size_t*
. The latter is most probably the cause of the segmentation fault.
精彩评论