Reputation: 423
I am programming a game of connect four server and client, and I need to transmit the game array to the client via a string.
I am trying to collect the array in a string variable, playerBoard
, using strcat
, but it seems that when it gets to the client, it displays garbage, and also, the server is showing me Segmentation fault
as an error
Server:
else
{
bzero(playersBoard, 100);
int k, j;
for( k = 0; k < HEIGTH; k++ )
{
for( j=0; j < WIDTH; j++ )
{
strcat(playersBoard, (char *)gameArray[k][j]);
strcat(playersBoard, " ");
}
}
strcat(playersBoard, "Now is your turn");
printf("Players board is : \n%s\n", playersBoard);
if(write(tdL.cl, playersBoard, 100) <= 0)
{
printf("[thread %d]\n", tdL.idThread);
perror("[thread] Error at write\n");
}
else
printf("[thread %d] Message was sent with success\n", tdL.idThread);
goto playerOneRetry;
}
Client:
if (write (sd, message, sizeof(message)) <= 0)
{
perror ("[client]Eroare la write() spre server.\n");
return errno;
}
char message2[100];
fflush(stdout);
if (read (sd, message2, 100 ) < 0)
{
perror ("[client]Eroare la read() de la server.\n");
return errno;
}
//writing message
printf ("[client]Message received is : %s\n", message2);
Upvotes: 0
Views: 56
Reputation: 409196
The expression gameArray[k][j]
is a single character, it's not a string. You can not use it as argument in strcat
. Trying to cast the character to char *
will turn the encoded character into a pointer which is not going to point to a valid string. Using it as such will lead to undefined behavior.
You can append a single character to a string like e.g.
playersBoard[strlen(playersBoard)] = gameArray[k][j];
playersBoard[strlen(playersBoard) + 1] = '\0';
You should really keep an eye on the warnings the compiler will emit, and without the cast it should have said something. Warnings are often a sing of you doing something you should not be doing, and disabling them is usually not a good idea as it only hides the symptom and not the problem.
Also be careful with casting, in most situations it's considered a code smell. If you find you need to cast something then you probably are doing something wrong as well.
The combination of warnings and casting is the worst of all, as like I said above you only hide the problem, but don't solve it.
Upvotes: 1
Reputation: 149
(char *)gameArray[k][j]
1e : (char *)gameArray[k][j] : why the cast ? gameArray[k][j] should be a 2 dim. array of type (char *). If you need to make the cast you probably defined it wrong which would cause the seg. fault.
2e : are you sure you don't overrun playersBoard ? That would cause it.
3e : bzero(playersBoard, 100); : the size of playersBoard is probably known. You should always try to avoid the static 100 and replace it by maybe : sizeof(playerBoard).
4e : You can prevent overrun of playersBoard. Using strncat and don't write more than you can. In the line of defensive programming .. you should.
Upvotes: 2