开发者

Why does the following code make my computer beep?

I'm having a really hard time understanding why is this piece of code making my computer beep. I've isolated thi开发者_Python百科s 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...


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜