c - Valgrind “大小为 1 的无效写入/读取”错误 memcpy
问题描述
我知道有人问过类似的问题。但是我仍然无法解决我的问题。因此,如果您能帮助我了解我做错了什么,我将不胜感激。我的程序基本上从文件中读取单词并将它们作为键/值对放入哈希表中。然后它将另一个文件中的单词与 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)
解决方案
当你这样做时:
char *y = malloc(sizeof(siz));
sizeof(size) 等于变量 siz 的字节数,即 size_t 的字节数。这真的是你想要的,还是你只是想做:
char *y = malloc(siz);
推荐阅读
- java - Hadoop S3A 文件系统,中止对象上传?
- reactjs - TextInput 元素顶部的按钮不起作用
- ffmpeg - 使用 ffmpeg 将 flac 转换为带有封面的 alac
- sql-server - SQL 触发器(更改事件)到 Azure 函数
- python - 为什么拟合的直线不适合图形?
- flutter - id3 包返回空值 - Dart
- java - 无法从 Firebase 检索数据到 ListView
- php - 无法在 php 循环中向 Div 添加正确的 id
- python - 如何反编译 Python 3.8.3 文件?
- c++ - Qt QSqlDatabase QSQLITE驱动程序未加载错误