簡體   English   中英

“在C中快速使用OpenSSL”程序因核心轉儲而中止

[英]“Quickly using OpenSSL in C” program aborts with core dump

我有一個函數會因核心轉儲而中止,除非插入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)

編輯 :我使用的修復程序發布在這里

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

您分配一個1024字節的緩沖區,然后向其中讀取1024字節,然后在緩沖區末尾寫入第1025個字節...

為了解決這個問題,我做了以下工作:

  1. 增加緩沖區大小如提到的克里斯·多德的答案在這里
  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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM