c-错误malloc():内存损坏



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

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)] = '';
  if (bytes < 0) {
      BIO_printf(outbio, "nError reading...n");
      exit(1);
  }
  received += bytes;
  BIO_printf(outbio, "Received...%d bytesn", received);
  BIO_printf(outbio, "%s", resp);
  BIO_printf(outbio, "Receive DONEn");
  return resp;
}

但是当我运行它时,我得到了错误:malloc():内存损坏。奇怪的是,当我主要在第二次调用这个函数时,它就会发生。第一时间还好。请帮我理解一下。

您的字符串尚未以''终止,因此您无法在其上调用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] = '';
  received += bytes;
  BIO_printf(outbio, "Received...%d bytesn", received);
  BIO_printf(outbio, "%s", resp);
  BIO_printf(outbio, "Receive DONEn");
  return resp;
}

另一种解决方案可以称为calloc而不是malloc。。。

相关内容

  • 没有找到相关文章

最新更新