I am practicing a client-server application in C. In the application, the client first registers with the server and gets the client_id
in return. Next time onwards, the client sends the messages to the server prepending the client_id
to the message. Below code snippet is from the server, where after receiving the message, the server retrieves the client_id
from the message, which is a 3 char long string with start address as 1 and end address as 4 from the message array. eg. In the message "1001CLIENT:001:MESSAGE:01"
, '1' at location 0 is for some purpose, "001" is the client_id
and "CLIENT:001:MESSAGE:01"
is the message from the client.
char *create_dynamic_string(int str_size)
{
char *dyn_string = malloc(str_size*sizeof(char));
if(!dyn_string)
{
printf("Dynamic string could not be created");
return NULL;
}
dyn_string[0] = '\0';
return dyn_string;
}
void free_dynamic_string(char *dyn_string)
{
free(dyn_string);
}
//char *message is dynamically allocated char array.
char *retrieve_client_id(char *message)
{
char *client_id;
int i;
client_id = create_dynamic_string(CLIENT_ID_SIZE + 1);
if(!client_id)
{
printf("Client_id is NULL");
return NULL;
}
//for(i = 1; i < (CLIENT_ID_SIZE + 1); i++)
// client_id[i-1] = message[i];
//strncpy(client_id, message + 1, CLIENT_ID_SIZE);
memcpy(client_id, message + 1, CLIENT_ID_SIZE);
client_id[CLIENT_ID_SIZE] = '\0';
printf("client_id retrieved=%s", client_id);
return client_id;
}
The server accepts a connection from the clients and processes the messages in different threads. The working on multi-threading and processing of the messages is tested successfully. Below code compiled successfully and works most of the times. But some times it ends up in segmentation fault at memcpy()
in retrieve_client_id()
. I am not able to figure out why is it failing this way.
I used gdb
to get more info. This is as below.
Program terminated with signal 11, Segmentation fault.
#0 0x00000000004017ef in retrieve_client_id (message=0x1b904f40 "1000CLIENT:000:MESSAGE:02") at src/server.c:46
46 memcpy(client_id, message + 1, CLIENT_ID_SIZE);
(gdb) print message
$1 = 0x1b904f40 "1000CLIENT:000:MESSAGE:02"
(gdb) print message+1
$2 = 0x1b904f41 "000CLIENT:000:MESSAGE:02"
(gdb) print CLIENT_ID_SIZE
$3 = 3
(gdb) print client_id
$4 = 0xffffffffcc0008c0 <Address 0xffffffffcc0008c0 out of bounds>
(gdb)
Need help in understanding what exactly might be happening when the application is failing. I have verified that the malloc
was successful and client_id
was not NULL. As you can see the commented code, I also tried with strcpy()
and also copying the chars from source to dest array one by one. But there also I saw the failures.