1

除非我插入 printf,否则我有一个使用核心转储中止的函数:

// Read all available text from the connection
char *sslRead (connection *c)
{
    const int readSize = 1024;
    char *rc = NULL;
    int received, count = 0;
    char buffer[1024];

    //  printf("??"); // If I comment this out: Aborted (core dumped)

    if (c)
    {
        while (1)
        {
            if (!rc)
                rc = malloc (readSize * sizeof (char) + 1);
            else
                rc = realloc (rc, (count + 1) *
                        readSize * sizeof (char) + 1);

            received = SSL_read (c->sslHandle, buffer, readSize);
            buffer[received] = '\0';

            if (received > 0)
                strcat (rc, buffer);

            if (received < readSize)
                break;
            count++;
        }
    }
    return rc;
}

malloc 似乎是违规行。

完整的源代码在这里:在 C 中快速使用 OpenSSL

这可能是什么原因造成的?

Below is the output from my build:

23:06:41 **** Incremental Build of configuration Debug for project HelloWorldOpenSSL ****
Info: Internal Builder is used for build
gcc "-IC:\\dev\\cygwin64\\opt\\cs\\include" -O0 -g3 -Wall -c -fmessage-length=0 -o MyC.o "..\\MyC.c" 
gcc "-LC:\\dev\\cygwin64\\opt\\cs\\lib" -o HelloWorldOpenSSL.exe MyC.o -lssl -lcrypto 

23:06:42 Build Finished (took 804ms)

编辑:我使用的修复程序发布在这里

4

2 回答 2

8
const int readSize = 1024;
char buffer[1024];
     :
received = SSL_read (c->sslHandle, buffer, readSize);
buffer[received] = '\0';

您分配一个 1024 字节的缓冲区,然后将 1024 字节读入其中,然后在缓冲区末尾写入第 1025 个字节...

于 2013-09-17T22:15:22.700 回答
0

为了解决这个问题,我做了以下事情:

  1. 如Chris Dodd在此处的回答中所述,增加了缓冲区大小。
  2. 在调试时,我注意到 strlen(rc) 比它应该的大得多,所以我在将 rc 字符串传递给 strcat 之前用 NULL 终止了它。

该代码现在似乎工作正常。

// Read all available text from the connection
char *sslRead (connection *c)
{
    const int readSize = 1024;
    char *rc = NULL;
    int received, count = 0;
    char buffer[1025];         // increased buffer

    if (c)
    {
        while (1)
        {
            if (!rc)
                rc = malloc (readSize * sizeof(char) + 1);
            else
                rc = realloc (rc, (count + 1) * readSize * sizeof(char) + 1);

            received = SSL_read (c->sslHandle, buffer, readSize);

            if (received > 0)
            {
                rc[count * readSize] = '\0';   // null terminate rc
                buffer[received] = '\0';
                strcat (rc, buffer);
            }

            if (received < readSize)
                break;
            count++;
        }
    }
    return rc;
}
于 2013-09-17T23:09:47.733 回答