當我編譯下面的短片段(在其中我們定義一個字符串,然後使用strdup做一個副本),我得到3個警告:來自GCC的2個編譯器警告和來自valgrind的1個運行時警告/錯誤。strdup():困惑於警告('隱式聲明','使指針...沒有投射',內存泄漏)
我懷疑內存泄漏錯誤(由valgrind報告)也與我使用strdup有關,這就是爲什麼我在下面包含相關輸出的原因。
我在做什麼錯? (我通過C書工作我的方式,這是的strdup是如何使用的作者。)
代碼:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char *string1 = "I love lamp";
char *string2;
string2 = strdup(string1);
printf("Here's string 1: %s\n"
"Here's string 2: %s\n",
string1, string2);
return 0;
}
的警告/輸出:
[email protected]:~/workspaceC/LearnCHW/Ex17_StructsPointers$ make test
cc -std=c99 test.c -o test
test.c: In function ‘main’:
test.c:9:3: warning: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration]
string2 = strdup(string1);
^
test.c:9:11: warning: assignment makes pointer from integer without a cast [enabled by default]
string2 = strdup(string1);
^
[email protected]:~/workspaceC/LearnCHW/Ex17_StructsPointers$ valgrind --track-origins=yes --leak-check=full ./test
==3122== Memcheck, a memory error detector
==3122== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3122== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==3122== Command: ./test
==3122==
Here's string 1: I love lamp
Here's string 2: I love lamp
==3122==
==3122== HEAP SUMMARY:
==3122== in use at exit: 12 bytes in 1 blocks
==3122== total heap usage: 1 allocs, 0 frees, 12 bytes allocated
==3122==
==3122== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3122== at 0x4C2ABBD: malloc (vg_replace_malloc.c:296)
==3122== by 0x4EBF2B9: strdup (strdup.c:42)
==3122== by 0x4005A4: main (in /home/dchaudh/workspaceC/LearnCHW/Ex17_StructsPointers/test)
==3122==
==3122== LEAK SUMMARY:
==3122== definitely lost: 12 bytes in 1 blocks
==3122== indirectly lost: 0 bytes in 0 blocks
==3122== possibly lost: 0 bytes in 0 blocks
==3122== still reachable: 0 bytes in 0 blocks
==3122== suppressed: 0 bytes in 0 blocks
==3122==
==3122== For counts of detected and suppressed errors, rerun with: -v
==3122== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
您還沒有爲'strdup'相關的頭通過GCC的命令行的定義。 – 2014-10-09 17:09:12
他做到了。 @OliverCharlesworth – alk 2014-10-09 17:17:35