Why does the following code make my computer beep?

拥有回忆 提交于 2019-12-20 05:19:27

问题


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...


回答1:


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.



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/4207034/why-does-the-following-code-make-my-computer-beep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!