当我编译下面的一小段代码(其中我们定义一个字符串,然后使用 strdup 来制作副本)时,我收到 3 个警告:来自 GCC 的 2 个编译器警告和来自 valgrind 的 1 个运行时警告/错误。
我怀疑内存泄漏错误(由 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;
}
警告/输出:
dchaudh@dchaudhUbuntu:~/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);
^
dchaudh@dchaudhUbuntu:~/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)
C标准库没有这样的函数strdup
。然而,这个流行的函数通常由标准库实现作为扩展提供。在 GCC 实现中,该函数声明于<string.h>
,你确实包括在内。
但是,当您使用更严格的标准设置编译代码时,例如-std=c99
,编译器隐藏标准库头中的非标准函数声明。这就是发生的事情strdup
您的情况的声明。您收到的警告是当您尝试调用未声明的函数时发出的典型警告。从形式上来说,从 C99 的角度来看,这是一个错误,但编译器认为在这种情况下发出警告就足够了。如果您删除-std=c99
从编译器的命令行切换,声明strdup
将变得可见,并且代码将在没有该警告的情况下进行编译。
从技术上讲,指定-std=c99
在命令行中让 GCC 定义__STRICT_ANSI__
宏,这会导致所有非 ANSI 函数声明从标准头文件中“消失”。
该函数仍然存在于库中,这就是为什么您的代码links适当地。请注意,这并不一定run正确地,因为编译器假设strdup
返回了一个int
,而实际上它返回一个指针。
valgrind 报告只是内存泄漏的结果。strdup
分配你应该分配的内存free
当你不再需要它时,你自己。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)