2014-02-23 19 views
0

我有以下代碼來聲明和分配堆上的字符串。我是否需要將 0分配給c中的malloc字符串?

char *string = malloc(10); 
string[9] = '\0'; 
strncpy(string, "welcometotherealworld", 9); 

printf("string: %s\n", string); 

我必須手動設置\0\以確保字符串結尾? string[9] = '\0';

或者,strncpy爲我做這個?

+0

使用釋放calloc(10的sizeof(字符));爲了確定。 –

回答

2

strncpy如果源字符串(第二個參數)的長度大於或等於第三個參數的值,則不終止目標數組。

所以在這裏:

strncpy(string, "welcometotherealworld", 9); 

strncpy不會空終止。

0

welcometotherealworld肯定比9個字符長,所以strncpy不應該隱式添加終止字符。

3

兩件事:第一個malloc(10)保留10個字節,string[10]地址第十一個字節,這是非法的。第二:是的,你必須將字符串[9]設置爲空,因爲根據standard如果源字符串比count長,strncpy不能確保字符串爲空。

0

strncpy(dest, source, n)將最多n個字節從source指向的緩衝區拷貝到dest的緩衝區指針中。但是,如果strlen(source)大於n,那麼strncpy將簡單地複製第一個n字節,並且不會終止具有空字節的字符串dest,因爲它沒有空間。因此,爲確保緩衝區source始終爲空,必須自己完成。你正在做什麼將始終保持你的緩衝區指向string空終止。

0

爲確保正確的'\0'結尾,代碼需要設置'\0'
malloc()不初始化string中的數據。

char *string = malloc(10); 
strncpy(string, "welcometotherealworld", 9 /* or 10 */); 
string[9] = '\0'; 

strncpy(char *s1, const char *s2, size_t n)寫入nchars1
它首次使用min(n, strlen(s2))chars2
如果需要更多,s2的其餘部分用空字符編寫。

0

strcpy將始終以\0終止目標字符串。 strncpy正常NULL終止字符串,但可能不會。它複製字符串的最大字節數(n),但不幸的是(根據有用的ABI)不會複製爲NULL,如果要複製的字節數(即源字符串的長度,包括終止的NULL )超過指定的長度(n)。因此,如果您複製字符串"1234567890"(十個字符加上NULL,如此11)並將10作爲strncpy的最後一個參數,則會得到一個未終止的10個字符的字符串。

下面是一些解決這個安全路線:

dest = malloc(10); /* allocate ten bytes */ 
strncpy (dest, src, 10); /* copy up to 10 bytes */ 
dest[9] = 0; /* overwrite the 10th byte with a zero if it was not one already */ 

dest = malloc(10); /* allocate ten bytes */ 
strncpy (dest, src, 9); /* copy up to 9 bytes */ 
dest[9] = 0; /* make the 10th byte zero */ 

dest = calloc(10, 1); /* allocate and zero ten bytes */ 
strncpy (dest, src, 9); /* copy up to 9 bytes, leaving the NULL in */ 
相關問題