c - 错误 malloc() : memory corruption

标签 c sockets openssl malloc httpresponse

我想从服务器接收消息响应,所以我编写了以下函数:

char * receive_response(SSL *ssl, BIO *outbio) {
  int bytes;
  int received = 0;
  char *resp;
  resp = (char *) malloc(4096*sizeof(char));
  bytes = SSL_read(ssl, resp, 4096);
  resp[strlen(resp)] = '\0';
  if (bytes < 0) {
      BIO_printf(outbio, "\nError reading...\n");
      exit(1);
  }
  received += bytes;
  BIO_printf(outbio, "Received...%d bytes\n", received);
  BIO_printf(outbio, "%s", resp);
  BIO_printf(outbio, "Receive DONE\n");
  return resp;
}

但我在运行时收到错误:malloc():内存损坏。 奇怪的是,当我在 main 中第二次调用这个函数时,就会出现这种情况。第一次是没问题的。请帮助我理解它。

最佳答案

您的字符串尚未以 '\0' 终止,因此您无法对其调用 strlen:

char * receive_response(SSL *ssl, BIO *outbio) {
  int bytes;
  int received = 0;
  char *resp;
  // add one extra room if 4096 bytes are effectivly got
  resp = malloc(4096+1);
  if (NULL == resp)
  { 
      perror("malloc");
      exit(1);
  }
  bytes = SSL_read(ssl, resp, 4096);
  if (bytes < 0) {
      BIO_printf(outbio, "\nError reading...\n");
      exit(1);
  }
  resp[bytes] = '\0';
  received += bytes;
  BIO_printf(outbio, "Received...%d bytes\n", received);
  BIO_printf(outbio, "%s", resp);
  BIO_printf(outbio, "Receive DONE\n");
  return resp;
}

另一种解决方案可能是调用 calloc 而不是 malloc...

关于c - 错误 malloc() : memory corruption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539118/

相关文章:

Android AsyncTask 和线程

C编程TCP服务器和客户端连接错误

c - DTLS:客户端重传超时/服务器消息等待超时

c - Scanf 在 C 中跳过每隔一个 while 循环

c - 需要帮助反转数组

c - 为什么不捕获 ebp 之上的堆栈写入以避免溢出漏洞?

c - C:为什么C需要char的内存地址才能将其转换为int?

java - 如何使用套接字进行线程以便程序不会停止

node.js - 使用 TLS 协议(protocol)运行 NodeJS

c++ - DER 格式的 X509 证书是否采用 ASN1 编码?