简体   繁体   English

错误malloc():内存损坏

[英]Error malloc(): memory corruption

I want to receive messages response from server so I wrote the function bellow: 我想从服务器接收消息响应,所以我写了下面的函数:

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;
}

But I get the error: malloc():memory corruption when I run it. 但是我得到了错误:运行时,malloc():内存损坏。 The strange thing is it occurs when I call this function at the second times in main. 奇怪的是,当我在main中第二次调用此函数时,它会发生。 It's ok at the first time. 第一次没关系。 Please help me to understand it. 请帮助我理解它。

Your string is not yet terminated with a '\\0' , so you can't call strlen on it: 您的字符串尚未以'\\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;
}

Another solution could be to called calloc instead of malloc ... 另一种解决方案是调用calloc而不是malloc ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM