我知道有人问过类似的问题。但是我仍然不能解决我的问题。因此,如果您能帮助我了解我在做什么错,我将非常感谢。我的程序基本上从文件中读取单词,并将它们作为键/值对放入哈希表中。然后,它将另一个文件中的单词与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)
答案 0 :(得分:4)
执行此操作时:
char *y = malloc(sizeof(siz));
sizeof(size)等于变量siz的字节数,即size_t的字节数。这真的是您想要的,还是您想要做的:
char *y = malloc(siz);