我正在使用以下代码创建一个' Key'用于测试哈希表(特别是,我正在测试删除项目所需的时间):
void remove_keys()
{
for (int i = 0; i < NUM_ITEMS; i++) {
char temp_key[20];
sprintf((char *)&temp_key, "Key: %d", i);
size_t key_len = strlen(temp_key) + 1;
char *key = malloc(sizeof(char) * (key_len));
sprintf(key, "%s", temp_key); // THIS LINE
htable_item *item = htable_item_search(root, key, key_len);
if (!item) {
printf("Item not found: %s\n", key);
} else {
//printf("Item found: %s - %s\n", key, item->value);
if (!htable_item_delete(root, item)) {
printf("Error while deleting: %s\n", key);
}
}
}
}
在我用评论标记的行中,有一种奇怪的行为。我正在使用sprintf来复制&#34; temp_key&#34;的内容。到&#34;键&#34;。在此之前,我使用strncpy来复制&#34; temp_key&#34;的内容。到&#34;关键&#34;但是我从这个操作得到的结果是这个(从XCode的调试器打印出来):
Printing description of key:
(char *) key = 0x0000000100103ed0 "Key: 10\xb0\xe7\x03\x01\x10"
while&#34; temp_key&#34;产生以下输出:
Printing description of temp_key:
(char [20]) temp_key = "Key: 10" {
[0] = 'K'
[1] = 'e'
[2] = 'y'
[3] = ':'
[4] = ' '
[5] = '1'
[6] = '0'
[7] = '\0'
[8] = '\0'
[9] = '\0'
[10] = '\0'
[11] = '\0'
[12] = '\0'
[13] = '\0'
[14] = '\0'
[15] = '\0'
[16] = '\0'
[17] = '\0'
[18] = '\0'
[19] = '\0'
}
哈希表使用memcmp来比较htable_item_search函数中的键。但是使用strncpy有一些项目(例如&#34; Key:10&#34;)在使用sprintf时找不到它完美无缺。为什么会出现这种差异?
答案 0 :(得分:3)
来自http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
如果source长于num,则不会在目标的末尾隐式附加空字符(因此,在这种情况下,目标可能不是空终止的C字符串)。
strncpy不会在你的字符串中添加一个null终止符,所以在使用这个函数时你的字符串末尾会有垃圾。