gpt4 book ai didi

c - Valgrind “invalid write/read of size 1” 错误 memcpy

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:45 25 4
gpt4 key购买 nike

<分区>

我知道有人问过类似的问题。但是我仍然无法解决我的问题。所以如果你能帮助我理解我做错了什么,我将非常感激。我的程序基本上从文件中读取单词并将它们作为键/值对放入哈希表中。然后它将来自另一个文件的单词与 HT 中的单词进行比较,如果找到它,则返回值...

    char *str_dup(const char *s) {
if (s == NULL) { // Optional test, s should point to a string
return NULL;
}
size_t siz = strlen(s) + 1;
char *y = malloc(sizeof(siz));
if (y != NULL) {
memcpy(y, s, siz);
}
return y;
}

int ht_put(HashTable *hashtable, const char *key, const char
*value){
List *node;

if (hashtable == NULL) {
return 2;
}

node = malloc(sizeof(List));
if (node == NULL) {
return 2;
}
node->key = str_dup(key);
node->value = str_dup(value);

node_handler(hashtable, node);

return 0;
}

HashTable *dict;
dict = ht_create(numKeys);
if(dict == NULL){
return 2;
}

char *val;
int cnt = 0;
while(fgets(buffer,1000000000,wb)) {
// Eliminate UNIX/DOS line terminator
val=strrchr(buffer,'\n');
if (val) *val=0;
val=strrchr(buffer,'\r');
if (val) *val=0;

//Find first occurrence of the separator ':'
val=strchr(buffer,':');
if (val) {
// Truncates buffer string to first word
// and (++) points second word
*val++=0;
}

if (cnt<1000000000) {
if (val!=NULL) {
if(ht_get(dict,buffer) == NULL){
ht_put(dict,buffer,val);
}
else {
ht_free(dict);
fclose(wb);
free(buffer);
fprintf(stderr,"Zwei Zeilen beschreiben
dasselbe deutsche Wort.\n");
exit(2);
return 2;
}
}
cnt++;
}
}
fclose(wb);
free(buffer);

这是 valgrind 显示的内容:

    ==478519== Invalid write of size 2
==478519== at 0x4C325E3: memcpy@GLIBC_2.2.5 (in
/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==478519== by 0x401701: strdup (loesung.c:62)
==478519== by 0x401701: ht_put (loesung.c:285)
==478519== by 0x400FA2: main (loesung.c:389)
==478519== Address 0x51fc958 is 0 bytes after a block of size
8 alloc'd
==478519== at 0x4C2E01F: malloc (in
/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==478519== by 0x4016EA: strdup (loesung.c:60)
==478519== by 0x4016EA: ht_put (loesung.c:285)
==478519== by 0x400FA2: main (loesung.c:389)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com