1

I'm having a really hard time understanding why is this piece of code making my computer beep. I've isolated this section of code to be the one producing the occasional beep, but I don't see what's the problem with it.

const int BUFFER_LENGTH = 8192;
char buffer [BUFFER_LENGTH + 1];
int recvResult;

do
{
    recvResult = recv(webSocket, buffer, BUFFER_LENGTH, 0);
    buffer[recvResult] = '\0';
    printf("%s", buffer);
    if (recvResult > 0)
    {
        sendResult = send(clientSocket, buffer, recvResult, 0);
    }
}while (recvResult > 0);

shutdown(webSocket, SD_SEND);

To give a little bit of context, this is for a computer networks class in which we have to code a proxy. So what I'm doing is listening to the answer and simply forward it to the client.

I can't tell you how high I jumped out of my chair when I first heard the beeping noise...

Gab Royer
  • 9,587
  • 8
  • 40
  • 58

3 Answers3

11

The buffer probably contains a '\a' char which makes the computer beep. From 5.2.2 (Character display semantics) :

Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:

  • \a (alert) Produces an audible or visible alert without changing the active position.
icecrime
  • 74,451
  • 13
  • 99
  • 111
1

Nevermind, found it, it was actually the printf statement that was doing an occasionnal beep!

Gab Royer
  • 9,587
  • 8
  • 40
  • 58
1

Agree with the '\a' beep explanation.

One more point about your code:

recvResult = recv(webSocket, buffer, BUFFER_LENGTH, 0);
buffer[recvResult] = '\0';

Note that recvResult will be -1 if there's an I/O error (or if you're working in the non-blocking mode and no data to read so far).

In such a case you'll write into forbidden memory, which is (damn, how I hate this phrase) undefined behavior. Simply speaking - memory overwrite, which is bad.

You should check for socket error before writing into buffer

valdo
  • 12,632
  • 2
  • 37
  • 67