错误malloc():内存损坏

时间:2016-07-23 07:01:06

标签: 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中第二次调用此函数时会发生这种情况。这是第一次没问题。请帮我理解。

1 个答案:

答案 0 :(得分:0)

您的字符串尚未以'\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 ...

相关问题