strdup()作为其他函数的入参会导致内存泄漏么

C语言 码拜 8年前 (2016-04-04) 1543次浏览
正常strdup()总是与free()成对出现,如 char *a = strdup(b); free(a);
假如strdup(b)没有赋值给一个指针,而是作为其他函数的入参呢,如 char *a = functionA( strdup(b), c );
这种情况下,strdup(b)申请的内存没有被free(),是不是就内存泄漏了?
求指导~~
解决方案

60


_strdup, _wcsdup, _mbsdup
Duplicate strings.
char *_strdup( const char *strSource );
wchar_t *_wcsdup( const wchar_t *strSource );
unsigned char *_mbsdup( const unsigned char *strSource );
Routine Required Header Compatibility
_strdup <string.h> Win 95, Win NT
_wcsdup <string.h> or <wchar.h> Win 95, Win NT
_mbsdup <mbstring.h> Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
Each of these functions returns a pointer to the storage location for the copied string or NULL if storage cannot be allocated.
Parameter
strSource
Null-terminated source string
Remarks
The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.
_wcsdup and _mbsdup are wide-character and multibyte-character versions of _strdup. The arguments and return value of _wcsdup are wide-character strings; those of _mbsdup are multibyte-character strings. These three functions behave identically otherwise.
Generic-Text Routine Mappings
TCHAR.H Routine  _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined
_tcsdup _strdup _mbsdup  _wcsdup
Because _strdup calls malloc to allocate storage space for the copy of strSource, it is good practice always to release this memory by calling the free routine on the pointer returned by the call to _strdup.
Example
/* STRDUP.C */
#include <string.h>
#include <stdio.h>
void main( void )
{
char buffer[] = “This is the buffer text”;
char *newstring;
printf( “Original: %s\n”, buffer );
newstring = _strdup( buffer );
printf( “Copy:     %s\n”, newstring );
free( newstring );
}
Output
Original: This is the buffer text
Copy:     This is the buffer text
String Manipulation Routines
See Also   memset, strcat, strcmp, strncat, strncmp, strncpy, _strnicmp, strrchr, strspn

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明strdup()作为其他函数的入参会导致内存泄漏么
喜欢 (0)
[1034331897@qq.com]
分享 (0)