gpt4 book ai didi

C: 带有 void* 指针的 memcpy 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:49 26 4
gpt4 key购买 nike

代码——主循环:

int handleClient (struct clientData* clientData)
{
void* Buffer = malloc (INET_BUFFER_SIZE); <-- VOID* BUFFER FOR RECV()
int listenSocket = clientData->listenSocket;
struct sockaddr_in clientAddress = clientData->clientAddress;

printf("Received connection from client %s:%d.\n", inet_ntoa(clientAddress.sin_addr), ntohs(clientAddress.sin_port));

while (1)
{
int packetSize;
if ((packetSize = recv(listenSocket, &Buffer, INET_BUFFER_SIZE, 0)) > 0)
{
if (packetSize == ECHO_SIZE)
{
handleEchoPacket(Buffer);
continue;
}

if (packetSize == MESSAGE_SIZE) <---THIS IS TRIGGERED BECAUSE OF PACKET SIZE
{
handleMessagePacket(Buffer);
continue;
}
}
}

代码 -- handleMessagePacket(void* Buffer):

void handleMessagePacket (void* Buffer)
{

void* localBuffer = (void*) malloc(INET_BUFFER_SIZE);
memcpy(localBuffer, Buffer, INET_BUFFER_SIZE); <--SEGFAULT
(...)
}

GDB -- 部分输出:

Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () (.....) <--Tells me it doesn't have source files, not relevant to the problem.

基本上,当我将一个内存块从空指针复制到本地缓冲区时,就会出现问题。两者都是相同类型的 malloc() 堆内存:void。欢迎提出任何建议或意见!

最佳答案

事情是这样的:当您将 Buffer 的地址传递给 recv 时,接收到的数据被放置在分配给您的缓冲区地址的空间中,即在堆栈上。当您随后调用 handleMessagePacket 时,您传递的地址不再有效:它已被 recv 覆盖!

recv 的调用中删除 & 应该可以解决这个问题:

if ((packetSize = recv(listenSocket, Buffer, INET_BUFFER_SIZE, 0)) > 0)
// ^^ No ampersand

一般来说,像这样的情况最好用内存分析器来诊断,比如 valgrind。该工具会立即告诉您,Buffer 写入的堆栈区域中存在无效写入,随后将接收到的数据作为指针取消引用(现在导致 SIGSEGV 的问题)是无效读取.

关于C: 带有 void* 指针的 memcpy 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471101/

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