当我用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==
有人可以帮我摆脱这个错误吗?这是什么意思?
答案 0 :(得分:0)
在main()
的客户端,确保dummy
包含一个至少包含3个字符和一个空终止符的字符串(因为每个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);
也存在潜在问题,因为您传递给此函数而不是参数的地址,而是参数的poitner的地址。这个coudl是正确的,但根据函数的签名可能是错误的。如果您对此感到困惑,请发布此功能的代码,以便我们检查。