gpt4 book ai didi

c - FD_SET 从无效内存地址读取?

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:05 25 4
gpt4 key购买 nike

**编辑:我找到了解决方案。**

对于那些敢于阅读以下内容的人,我有一个奇怪的问题:

我正在做家庭作业,需要使用 UNIX 管道在进程之间发送消息。

我对这段代码的意图是对提供的文件描述符进行 select()。如果可以无阻塞地阅读某些内容,我想将其归还。如果不是,我想返回 NULL 并继续不阻塞。

这是我的“getMessage”函数中的代码,其中 fd 是文件描述符:

message* getMessage(int fd){
int messageAvailable = 0;
struct timeval timeout;
fd_set fd2;

//If there's a message available, read it; if not, continue on without delay
timeout.tv_sec = 0;
timeout.tv_usec = 0;
FD_ZERO(&fd2);
FD_SET(fd,&fd2);
messageAvailable = select(FD_SETSIZE,&fd2,NULL,NULL,&timeout);
if(messageAvailable){
int bytesRead = 0;
message* m;
m = malloc(sizeof(message));
//Get the header
bytesRead = read(fd,m,sizeof(message));
//If we got the whole message
if(bytesRead == sizeof(message)){
return m;
}else{
//If a message wasn't generated, free the space we allocated for it
free(m);
return NULL;
}
}else{
return NULL;
}
}

此代码位于一个循环内,该循环在程序运行期间一直持续,并且恰好在同一点(一条消息成功传输后的下一个 getMessage() 调用)出现段错误。显然,FD_SET 行正在从无效的内存位置读取。

在不发布我的所有代码的情况下,任何人都可以猜测是什么导致了这个简单宏中的段错误吗?

相关调试信息我贴在下面,其中第33行对应上面的FD_SET行:

==1330== Invalid read of size 1
==1330== at 0x804E819: getMessage (messages.c:33)
==1330== by 0x8049123: main (messageTest.c:110)
==1330== Address 0xde88d627 is not stack'd, malloc'd or (recently) free'd
==1330==
==1330==
==1330== Process terminating with default action of signal 11 (SIGSEGV)
==1330== Access not within mapped region at address 0xDE88D627
==1330== at 0x804E819: getMessage (messages.c:33)
==1330== by 0x8049123: main (messageTest.c:110)
==1330== If you believe this happened as a result of a stack
==1330== overflow in your program's main thread (unlikely but
==1330== possible), you can try to increase the size of the
==1330== main thread stack using the --main-stacksize= flag.
==1330== The main thread stack size used in this run was 8388608.
==1330==
==1330== HEAP SUMMARY:
==1330== in use at exit: 344 bytes in 10 blocks
==1330== total heap usage: 25 allocs, 15 frees, 2,492 bytes allocated
==1330==
==1330== LEAK SUMMARY:
==1330== definitely lost: 12 bytes in 1 blocks
==1330== indirectly lost: 0 bytes in 0 blocks
==1330== possibly lost: 0 bytes in 0 blocks
==1330== still reachable: 332 bytes in 9 blocks
==1330== suppressed: 0 bytes in 0 blocks
==1330== Rerun with --leak-check=full to see details of leaked memory
==1330==
==1330== For counts of detected and suppressed errors, rerun with: -v
==1330== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 11 from 6)
Segmentation fault

最佳答案

糟糕...在我进行了一些处理后,我不小心将 -1 作为 FD 传递给函数(这解释了为什么它在每次运行中都发生在同一点)。

这个问题大概可以关闭;我不认为它在我的单一用例之外有多大用处。

关于c - FD_SET 从无效内存地址读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9574048/

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