用法:#include <string.h>
The strdup() function allocates memory and copies into it the string addressed by s1, including the terminating null character. It is the user's responsibility to free the allocated storage by calling free() .
strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,这个副本有自己的内存空间,和s不相干。
char *strdup(const char *s)
{
}
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer to a new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(3), and can be freed with free(3).
The strndup() function is similar, but only copies at most n charac-
ters. If s is longer than n, only n characters are copied, and a termi-
nating NUL is added.
这里有一个问题就是strdup函数返回的字符串指针是由malloc在函数内部分配的,那么谁来释放这个动态内存呢?
程序员?还是系统?呵呵,真得很难回答。个人关点是这种做法尽量避免,函数内申请动态内存,而在函数外让程序员来释放,不过每个人都有每个人的观点,呵呵,下面是一个测试例子(无错误处理机制):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int Test()
{
char buf[]="Hello,World!";
char* pb = strndup(buf,strlen(buf));
return (unsigned int)(pb);
}
int main()
{
unsigned int pch = Test();
printf("Testing:%s\n", (char*)pch);
free((void*)pch);
return 0;
}
在Test函数里使用strndup而出了Test函数仍可以操作这段内存,并且可以释放。
由这个问题而延伸出来的问题就是,如何让函数得到的内存数据传出函数但仍可用。
解决方法目前本人只想到两个:
另一类方法就是上面所述的,利用堆里的内存来实现,但存在危险。
strdup是从堆中分配空间的!
strdup调用了malloc,所以它需要释放!
对于堆栈:
堆是由程序员来管理的,比如说new ,malloc等等都是在堆上分配的!
栈是由编译器来管理的。
strdup的工作原理:
char *
__strdup (const char *s)
{
size_t len = strlen (s) + 1;
void *new = malloc (len);
if (new == NULL)
return NULL;
return (char *) memcpy (new, s, len);
}
Duplicates a string.
Syntax
LPTSTRStrDup( LPCTSTR lpsz );
Parameters
lpsz
- A pointer to a constant null-terminated character string.
Return Value
Returns the address of the string that was copied, or NULL if the string cannot be copied.
Remarks
StrDup will allocate storage the size of the original string. If storage allocation is successful, the original string is copied to the duplicate string.
This function uses LocalAlloc to allocate storage space for the copy of the string. The calling application must free this memory by calling the LocalFree function on the pointer returned by the call to StrDup.
Example
This simple console application illustrates the use of StrDup.
#include <windows.h> #include <shlwapi.h> #include <stdio.h> void main(void) { char buffer[] = "This is the buffer text"; char *newstring; // Note: Never use an unbounded %s format specifier in printf. printf("Original: %25s\n", buffer); newstring = StrDup(buffer); if (newstring != NULL) { printf("Copy: %25s\n", newstring); LocalFree(newstring); } } OUTPUT: - - - - - - Original: This is the buffer text Copy: This is the buffer text