gpt4 book ai didi

c - 错误 malloc() : memory corruption

转载 作者:行者123 更新时间:2023-11-30 16:58:48 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com