gwar666
gwar666

Reputation: 13

Segmentation fault on sending text from file from server to client

I'm currently still programming a simple client-server application in C via Ubuntu. So far my login function seems to have worked well (enter some text in client, grab text from a file in server and verify), but this particular display option is giving me trouble.

Some snippets of the server-side code (I grabbed the file copy to buffer function below from another site):

char bflag[1]; //mainmenu option recveived from client
 char buffer[BUFSIZE+1]; //BUFSIZE is 1024
 long lSize;
 size_t result;

 FILE * userf;
 userf = fopen("Books.txt", "r+b");

 recv(new_sockfd, bflag, BUFSIZE, 0); //receive flag from clientside

 if ( (strncmp (bflag, "a", 1)) == 0) //display flag received
 {
  fseek (userf , 0 , SEEK_END);
  lSize = ftell (userf);
  rewind (userf);

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,userf);

  send(new_sockfd, buffer, BUFSIZE, 0);

 }
fclose(userf);

And on the client side, utilizing a switch for the various options:

char bbuf[BUFSIZE+1]; //BUFSIZE is 1024

switch (mmenuc)
{
 case 1:
{
 strcpy (mmenuf, "a"); 
 send (sockfd, mmenuf, BUFSIZE,0);//send flag 'a' to server

 system("clear");
 printf("Listing of books available:\n");
 printf("O = Available    X = Unavailable\n");
 printf("\n");

 recv (sockfd, bbuf, BUFSIZE,0);
 printf ("%s", bbuf);

 printf("\n");

 getchar(); //eats the "\n" 
 getchar(); //to pause
 break;
}

The problem that I am facing now is that the all the text in the file is retrieved and appears on the client side terminal fine, but on the server side terminal it gives a Segmentation Fault. I assume there's a buffer overflow somewhere, but I'm not sure what's causing it. Also, the Books.txt file is padded with spaces for an editing function later.

Upvotes: 0

Views: 511

Answers (1)

user1182692
user1182692

Reputation: 33

The server probably stores something like "a< cr >< lf >" in the buffer "Bflag". Not good. Should cause an error, but does not always cause one immediately.

You do not need to figure out the size of your file before you do the read:

Just issue: result = fread (buffer,1,BUFSIZE,userf); Now, if your file ends up being larger than the buffer, your program won't crash but just not read all the file. You can change your working program later on to handle the case that the file is larger than one buffer. Use "result" (if it is larger than zero) for the number of bytes-to-write to the client.

If your file is (more than a few bytes) larger than BUFSIZE, it will probably cause a "segmentation fault" on exit of the function you provided in the first codeblock. I think that's where your segmentation fault comes from.

Upvotes: 1

Related Questions