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

// C program to demonstrate strdup() 
#include<stdio.h> 
#include<string.h> 

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 <stdio.h> 
#include <string.h> 
#include <stdlib.h>

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; 
}