我有以下代碼來聲明和分配堆上的字符串。我是否需要將 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分配給c中的malloc字符串?
char *string = malloc(10);
string[9] = '\0';
strncpy(string, "welcometotherealworld", 9);
printf("string: %s\n", string);
我必須手動設置\0\
以確保字符串結尾? string[9] = '\0';
或者,strncpy
爲我做這個?
strncpy
如果源字符串(第二個參數)的長度大於或等於第三個參數的值,則不終止目標數組。
所以在這裏:
strncpy(string, "welcometotherealworld", 9);
strncpy
不會空終止。
welcometotherealworld
肯定比9
個字符長,所以strncpy
不應該隱式添加終止字符。
兩件事:第一個malloc(10)
保留10個字節,string[10]
地址第十一個字節,這是非法的。第二:是的,你必須將字符串[9]設置爲空,因爲根據standard如果源字符串比count長,strncpy不能確保字符串爲空。
strncpy(dest, source, n)
將最多n
個字節從source
指向的緩衝區拷貝到dest
的緩衝區指針中。但是,如果strlen(source)
大於n
,那麼strncpy
將簡單地複製第一個n
字節,並且不會終止具有空字節的字符串dest
,因爲它沒有空間。因此,爲確保緩衝區source
始終爲空,必須自己完成。你正在做什麼將始終保持你的緩衝區指向string
空終止。
爲確保正確的'\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)
寫入n
char
到s1
。
它首次使用min(n, strlen(s2))
char
從s2
。
如果需要更多,s2
的其餘部分用空字符編寫。
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 */
使用釋放calloc(10的sizeof(字符));爲了確定。 –