strdup函數的使用方法

來源:互聯網
上載者:User

標籤:style   color   使用   os   資料   io   

函數名: 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函數仍能夠操作這段記憶體,而且能夠釋放。

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

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

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

棧是由編譯器來管理的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.