【问题标题】:g_hash_table_insert malloc(): memory corruptiong_hash_table_insert malloc():内存损坏
【发布时间】:2014-03-20 05:15:23
【问题描述】:

我会尝试在 Glib 哈希中存储许多列表(数组)。这是示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

#define NR 10

typedef unsigned char carr[NR];

GHashTable* hasht;
int init = 0;


int main() {

    carr *c, *d;
    int i;

    hasht = g_hash_table_new(g_str_hash, g_str_equal);
    c = g_malloc0(sizeof *c);

    for(i=0; i<NR; i++) {
    *c[i] = 70+i;
    }

    for(i=0; i<NR; i++) {
    printf("%d\n", *c[i]);
    }

    g_hash_table_insert(hasht, "1", c);

    printf("----------------\n");
    d = g_hash_table_lookup(hasht, "1");
    for(i=0; i<NR; i++) {
    printf("%d\n", *d[i]);
    }

    return 0;
}

你可以用这种方式编译这段代码:

gcc -Wall -o arrtest arrtest.c `pkg-config --cflags --libs glib-2.0`

如果我运行编译后的代码,我会得到这个错误:

*** Error in `./arrtest': malloc(): memory corruption: 0x00000000018efe70 ***

但是如果我改变上面两行的顺序:

hasht = g_hash_table_new(g_str_hash, g_str_equal);
c = g_malloc0(sizeof *c);

到这里:

c = g_malloc0(sizeof *c);
hasht = g_hash_table_new(g_str_hash, g_str_equal);

代码运行没有任何问题。

为什么?

该项目将存储许多列表,如下所示:

a = {0, 1, 3, 4, 2, 0, 5, 9, 20};

每个列表都有一个字符串键。函数应该是这样的:

store_in_hash(char * key, int idx)

从其他地方打来的。该函数检查全局哈希表是否存在,如果不存在,则创建它。然后查找键,如果不存在,则创建一个新键,并增加列表的第 idx 项。将许多列表存储在哈希表中的预期方式是什么?

感谢您的帮助:

空气

【问题讨论】:

  • 你试过使用 valgrind 吗?
  • 我从未使用过 valgrind :)。首先,没有它我会解决这个问题,但我会看到的 - 谢谢。
  • 顺便说一句,*c[i] = 70+i;(和类似的代码)没有按照您的想法做。
  • 好吧,如果我将 'unsigned char' 更改为简单的 'int',那么它可以工作......为什么? :)
  • 好的,那有什么问题?在这种情况下,*c[i] 是一个无符号字符,是不是 [0..255]?

标签: c glib memory-corruption


【解决方案1】:

这里的问题是运算符优先级:

*c[i] = 70+i;

数组索引发生在指针取消引用之前。所以你想要(*c)[i]。顺便说一句,我会避免这种令人困惑的代码风格;您的 typedef 不是必需的,只需使用 char 指针,您就不会陷入这种奇怪的情况。

【讨论】:

  • 谢谢,这行得通 :) 现在我要找出有什么不同 :) 无论如何,我知道 typedef 不是必需的,我可以在任何地方使用 char[NR]。但我担心 char 指针应该更令人困惑......再次感谢!
  • *c[0] 工作;但是*c[1] 的意思是“取消引用 c + sizeof(*c) 处的地址”,所以你试图读取 malloc 的内存块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 2011-06-04
  • 1970-01-01
相关资源
最近更新 更多