1
**編輯:我已經找到了解決辦法**FD_SET從無效內存地址讀取?
我對那些誰也不敢下面讀一個奇怪的問題:
我工作的家庭作業,並且需要發送使用UNIX管道的進程之間的消息。
我用這段代碼的意圖是在提供的文件描述符上選擇()。如果有東西可以不阻塞地閱讀,我想返回它。如果不是,我想返回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
可以發佈更多的代碼,我可以看到沒有什麼明顯錯誤的發佈內容。除了如果'select()'失敗,它返回'-1'並且'if(messageAvailable)'將評估爲'true':改爲'if(messageAvailable> 0)'。爲什麼不對'select()'的第一個參數使用'fd +'1? – hmjd 2012-03-05 21:31:05
是的......很含糊的問題;對此我很抱歉。不過,我找到了解決方案。原來我傳遞一個無效的文件描述符到getMessage。 關於我的消息的好處可用警衛;我會改變它。謝謝 :) – BraedenP 2012-03-05 21:44:30