函式名: strdup

功  能: 將串複製到新建的位置處

用  法: char *strdup(char *str);

這個函式在linux的man手冊裡解釋為:

The strdup() function returns a pointer toa new string which is a

duplicate of the string s. Memory for thenew string is obtained with

malloc(3), and can be freed with free(3).

The strndup() function is similar, but onlycopies at most n charac-

ters. If s is longer than n, only ncharacters are copied, and a termi-

nating NUL is added.

strdup函式原型:

strdup()主要是拷貝字串s的一個副本,由函式返回值返回,這個副本有自己的記憶體空間,和s不相干。strdup函式複製一個字串,使用完後要記得刪除在函式中動態申請的記憶體,strdup函式的引數不能為NULL,一旦為NULL,就會報段錯誤,由於該函式包含了strlen函式,而該函式引數不能是NULL。

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

}

例項1:

C/C++ code

#include <stdio.h>

#include <string.h>

#include <alloc.h>

int main(void)

{

char *dup_str,*string = "abcde";

dup_str =strdup(string);

printf("%s\n", dup_str);free(dup_str); return 0;

}

例項2:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

unsigned int Test()

{

charbuf[]="Hello,World!";

char* pb =strndup(buf,strlen(buf));

return (unsignedint)(pb);

}

int main()

{

unsigned int pch= Test();

printf("Testing:%s\n",(char*)pch);

free((void*)pch);

return 0;

}

在Test函式裡使用strndup而出了Test函式仍能夠操作這段記憶體,而且能夠釋放。

由這個問題而延伸出來的問題就是,怎樣讓函式得到的記憶體資料傳出函式但仍可用。

解決方法眼下本人僅僅想到兩個: 一個外部變數,如傳遞一個記憶體塊指標給函式,但這樣的做法就是你得傳遞足夠的記憶體,也就是你不能事先知道這個函式究竟要多大的BUFFER。

還有一種方法就是在函式內部申請static變數,當然這也是全域性區的變數,但這樣的做法的缺點就是,當函式多次執行時,static變數裡面的資料會被覆蓋。這樣的型別的還有一個方法就是使用全域性變數,但這和使用static變數非常同樣,不同的是全域性變數能夠操作控制,而static變數假設不把它傳出函式,就不可對它操作控制了。還有一類方法就是上面所述的,利用堆裡的記憶體來實現,但存在危急。strdup是從堆中分配空間的!strdup呼叫了malloc,所以它須要釋放!對於堆疊:堆是由程式猿來管理的,比方說new,malloc等等都是在堆上分配的!

棧是由編譯器來管理的。