当我用 valgrind 运行它时,我在客户端得到以下输出:
==7374== Memcheck, a memory error detector
==7374== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==7374== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==7374== Command: ./rvotefor localhost bush 1
==7374==
==7374== Use of uninitialised value of size 8
==7374== at 0x4C2AD40: strcpy (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==7374== by 0x400A1C: vote_prog_1 (rvotefor.c:17)
==7374== by 0x400BF8: main (rvotefor.c:84)
==7374==
==7374== Invalid write of size 1
==7374== at 0x4C2AD40: strcpy (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==7374== by 0x400A1C: vote_prog_1 (rvotefor.c:17)
==7374== by 0x400BF8: main (rvotefor.c:84)
==7374== Address 0x2 is not stack'd, malloc'd or (recently) free'd
==7374==
==7374==
==7374== Process terminating with default action of signal 11 (SIGSEGV)
==7374== Access not within mapped region at address 0x2
==7374== at 0x4C2AD40: strcpy (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==7374== by 0x400A1C: vote_prog_1 (rvotefor.c:17)
==7374== by 0x400BF8: main (rvotefor.c:84)
==7374== If you believe this happened as a result of a stack
==7374== overflow in your program's main thread (unlikely but
==7374== possible), you can try to increase the size of the
==7374== main thread stack using the --main-stacksize= flag.
==7374== The main thread stack size used in this run was 8388608.
==7374==
==7374== HEAP SUMMARY:
==7374== in use at exit: 0 bytes in 0 blocks
==7374== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==7374==
==7374== All heap blocks were freed -- no leaks are possible
==7374==
==7374== For counts of detected and suppressed errors, rerun with: -v
==7374== Use --track-origins=yes to see where uninitialised values come from
==7374== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)
Segmentation fault
这是在服务器端:
==6841== Memcheck, a memory error detector
==6841== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==6841== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==6841== Command: ./vote_server
==6841==
谁能帮我解决这个错误?什么意思?
最佳答案
在 main()
的客户端,您确保 dummy
包含一个至少包含 3 个字符和一个空终止符的字符串(因为至少有 1 个每个 argv 2 和 argv[3] 中的字符)。
当您随后调用 vote_prog_1()
时,第一条语句是:
char * votefor_1_arg; // <===== !! uninitialized pointer
strcpy(votefor_1_arg,dummy); // <===== !! copy the more than 4 bytes in dummy
因此,您用 dummy[]
中包含的至少 4 个字节覆盖了某处内存(未初始化的指针),从而破坏了内存。
你必须在使用你的指针之前分配内存。例如 strdup()
(linux 或 windows):
votefor_1_art = strdup(dummy); // <== allocates memory and copy the string
votefor_1(&votefor_1_arg, clnt);
也存在潜在问题,因为您传递给此函数的不是参数地址,而是参数指针的地址。这可能是正确的,但也可能是错误的,具体取决于函数的签名。如果您对此感到困惑,请将此功能的代码也贴出来,以便我们检查。
关于c - 在 RPC 代码中获取 memcheck 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29063052/