C++ char 指针大小在 malloc 之后超出
C++ char pointer size exceeds after malloc
我有一个 char 指针并且使用过类似的 malloc
char *message;
message=(char *)malloc(4000*sizeof(char));
稍后我从消息中的套接字接收数据如果数据超过 4000 字节会怎样?
我假设你问的是如果你这样做会发生什么:
recv(socket,message,5000,0);
并且读取的数据量大于4000
这将是未定义的行为,因此您需要确保它不会发生。每当您从套接字读取时,您应该能够指定要读取的最大字符数。
您的问题遗漏了许多有关网络协议的细节,请参阅@DavidSchwartz 的回答。
但请注意存储它的缓冲区:如果您尝试将超过 4K 的字符写入 message
分配的内存中,您的程序可能会崩溃。
如果您测试收到的邮件的大小,您可以 realloc
:
int buf_len = 4000;
char *message;
message = static_cast<char*>(malloc(buf_len));
/* read message, and after you have read 4000 chars, do */
buf_len *= 2;
message = static_cast<char*>(realloc(message, buf_len));
/* rinse and repeat if buffer is still too small */
free(message); // don't forget to clean-up
但这非常耗费人力。只需使用 std::string
int buf_len = 4000;
std::string message;
message.reserve(buf_len); // allocate 4K to save on repeated allocations
/* read message, std::string will automatically expand, no worries! */
// destructor will automatically clean-up!
这取决于几个因素。假设您的代码中没有错误,这将取决于您使用的协议。
如果是 TCP,您将永远不会获得比您要求的更多的字节。下次调用接收函数时,您将获得更多数据。
如果是 UDP,你可能会被截断,你可能会得到一个错误(比如 MSG_TRUNC
)。这取决于您平台的具体情况以及您调用接收函数的方式。我知道没有平台会为您下次调用接收函数保存部分数据报。
当然,如果您的代码中存在错误并且您实际上溢出了缓冲区,则可能会发生非常糟糕的事情。因此,请确保您只将合理的值传递给您正在使用的任何接收函数。
为了获得最佳结果,您会收到分段错误
见
What is a segmentation fault?
我有一个 char 指针并且使用过类似的 malloc
char *message;
message=(char *)malloc(4000*sizeof(char));
稍后我从消息中的套接字接收数据如果数据超过 4000 字节会怎样?
我假设你问的是如果你这样做会发生什么:
recv(socket,message,5000,0);
并且读取的数据量大于4000
这将是未定义的行为,因此您需要确保它不会发生。每当您从套接字读取时,您应该能够指定要读取的最大字符数。
您的问题遗漏了许多有关网络协议的细节,请参阅@DavidSchwartz 的回答。
但请注意存储它的缓冲区:如果您尝试将超过 4K 的字符写入 message
分配的内存中,您的程序可能会崩溃。
如果您测试收到的邮件的大小,您可以 realloc
:
int buf_len = 4000;
char *message;
message = static_cast<char*>(malloc(buf_len));
/* read message, and after you have read 4000 chars, do */
buf_len *= 2;
message = static_cast<char*>(realloc(message, buf_len));
/* rinse and repeat if buffer is still too small */
free(message); // don't forget to clean-up
但这非常耗费人力。只需使用 std::string
int buf_len = 4000;
std::string message;
message.reserve(buf_len); // allocate 4K to save on repeated allocations
/* read message, std::string will automatically expand, no worries! */
// destructor will automatically clean-up!
这取决于几个因素。假设您的代码中没有错误,这将取决于您使用的协议。
如果是 TCP,您将永远不会获得比您要求的更多的字节。下次调用接收函数时,您将获得更多数据。
如果是 UDP,你可能会被截断,你可能会得到一个错误(比如 MSG_TRUNC
)。这取决于您平台的具体情况以及您调用接收函数的方式。我知道没有平台会为您下次调用接收函数保存部分数据报。
当然,如果您的代码中存在错误并且您实际上溢出了缓冲区,则可能会发生非常糟糕的事情。因此,请确保您只将合理的值传递给您正在使用的任何接收函数。
为了获得最佳结果,您会收到分段错误
见
What is a segmentation fault?