"在C中快速使用OpenSSL"程序会因核心转储而中止

Chr*_*now 1 c

除非我插入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;
}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*odd 8

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

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

  • @Chris:这是*未定义的行为*.你写第1025个字节的那一刻就会发生任何事情.对`printf()`的调用可能导致编译器改变堆栈框架内局部变量的布局,足以将结果从"崩溃"更改为"静默破坏内存",但它仍然是未定义的行为. (6认同)
  • 未定义的行为意味着实现可以做任何事情,无论是否合乎逻辑.它可以格式化你的硬盘,如果你要相信C标准......这里没有必要寻找原因,只需将1024更改为1025 ... (2认同)