2013-02-19 67 views
10

我打電話給strdup,並且在致電strdup之前必須爲變量分配空間。如何使用strdup?

char *variable; 
variable = (char*) malloc(sizeof(char*)); 
variable = strdup(word); 

我做對了嗎?或者這裏有什麼不對嗎?

回答

17

如果您使用的是POSIX標準strdup(),它會計算所需的空間並分配它並將源字符串複製到新分配的空間中。你不需要自己做malloc();實際上,如果你這樣做了,它會立即泄漏,因爲你只用指針指向分配的空間的指針來覆蓋指向空間的唯一指針。

因此:

char *variable = strdup(word); 
if (variable == 0) …process out of memory error; do not continue… 
…use variable… 
free(variable); 

如果您需要做的內存分配,那麼你需要在variable分配strlen(word)+1字節,那麼你就可以word複製到新分配的空間。

char *variable = malloc(strlen(word)+1); 
if (variable == 0) …process out of memory error; do not continue… 
strcpy(variable, word); 
…use variable… 
free(variable); 

,或者一旦計算長度並用memmove()或許memcpy()

size_t len = strlen(word) + 1; 
char *variable = malloc(len); 
if (variable == 0) …process out of memory error; do not continue… 
memmove(variable, word, len); 
…use variable… 
free(variable); 

不要忘記,以確保您知道free()是每malloc()

2

就目前而言,您總是泄露4至8個字節(取決於您的架構)。無論strdup哪個will allocate the required dynamic memory on its own您都重新分配了唯一的變量,該變量將指針保存到您最近的mableced內存區域。

簡單的說

char* const variable = strdup(word); 
9

你不需要的alloc空間與使用的strdup,會的strdup爲你做的。但是你應該在使用後釋放它。

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <assert.h> 

int main(){ 

    const char* s1= "Hello World"; 
    char* new = strdup (s1); 
    assert (new != NULL); 

    fprintf(stdout , "%s\n", new); 

    free (new); 
    return 0; 
} 

編輯:要當心用C++作爲新的變量名是好的C和在C++中,因爲它是運營商新的保留名稱。

+0

你不應該使用'new'變量名 – 2017-01-23 11:04:55

+0

@ ALE-棉絮變量名是C.完全正常不過,我可以理解C++編譯器不喜歡它。這個問題被標記爲C.因此,我沒有看到問題。 – hetepeperfan 2017-01-23 12:59:43

6

你似乎很困惑。忘記你對指針的瞭解。讓我們用int整理。

int x; 
x = rand(); // Let us consider this the "old value" of x 
x = getchar(); // Let us consider this the "new value" of x 

有沒有什麼辦法讓我們來檢索舊值,或已經從我們的觀點「泄密」?作爲一個假設,假設您希望操作系統知道您已完成該隨機數,以便操作系統執行一些清理任務。

產生新價值所需的舊價值?怎麼可能,getchar看不見x?

現在讓我們考慮您的代碼:

char *variable; 
variable = (char*) malloc(sizeof(char*)); // Let us consider this the "old value" of variable 
variable = strdup(word);     // Let us consider this the "new value" of variable 

有沒有什麼辦法讓我們來檢索舊值,或已經從我們的觀點「泄密」?通過調用free(variable);,您可以通過操作系統知道何時完成malloc ed內存。

產生新價值所需的舊價值?當strdup看不到變量時怎麼會這樣?

僅供參考,這裏有一個如何的strdup可能實現的一個例子:

char *strdup(const char *original) { 
    char *duplicate = malloc(strlen(original) + 1); 
    if (duplicate == NULL) { return NULL; } 

    strcpy(duplicate, original); 
    return duplicate; 
}