c语言 函数strdup,strdup函数使用误区

在项目中看到有同事使用strdup函数后没有释放内存,在google搜索后发现许多网站中给的代码例子中使用完之后并未释放内存,存在一定程度上的误导。

// C program to demonstrate strdup()

#include

#include

int main()

{

char source[] = "GeeksForGeeks";

// A copy of source is created dynamically

// and pointer to copy is returned.

char* target = strdup(source);

printf("%s", source);

return 0;

}

上面代码未释放target指针所指向的内存,因此存在内存泄露,使用valgrind验证结果如下:

[root@centos-7 workspace]# valgrind --leak-check=yes ./strdup

==9264== Memcheck, a memory error detector

==9264== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.

==9264== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info

==9264== Command: ./strdup

==9264==

GeeksForGeeks

==9264==

==9264== HEAP SUMMARY:

==9264== in use at exit: 14 bytes in 1 blocks

==9264== total heap usage: 1 allocs, 0 frees, 14 bytes allocated

==9264==

==9264== 14 bytes in 1 blocks are definitely lost in loss record 1 of 1

==9264== at 0x4C29E33: malloc (vg_replace_malloc.c:299)

==9264== by 0x4EC3809: strdup (in /usr/lib64/libc-2.17.so)

==9264== by 0x40058B: main (strdup.c:11)

==9264==

==9264== LEAK SUMMARY:

==9264== definitely lost: 14 bytes in 1 blocks

==9264== indirectly lost: 0 bytes in 0 blocks

==9264== possibly lost: 0 bytes in 0 blocks

==9264== still reachable: 0 bytes in 0 blocks

==9264== suppressed: 0 bytes in 0 blocks

==9264==

==9264== For counts of detected and suppressed errors, rerun with: -v

==9264== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

[root@centos-7 workspace]#

正确的程序如下:

// C program to demonstrate strdup()

#include

#include

#include

int main()

{

char source[] = "GeeksForGeeks";

// A copy of source is created dynamically

// and pointer to copy is returned.

char* target = strdup(source);

printf("%s\n", source);

free(target);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值