欢迎光临
我们一直在努力

c语语言转换函数,r语言函数

在项目中看到有同事使用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 美国高防vps 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;

}

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。