使用GHashTable的GLib-CRITICAL错误

时间:2016-08-09 23:18:57

标签: c hashtable glib

我正在尝试使用GLib创建一种缓存函数输出的方法,以便将来快速计算。以下是我正在使用的实现示例...

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

static GHashTable *table;

double P_l(double x,int lmax){
  //double pl;
  double p[lmax+2];
  int l;

  p[0] = 1.;
  p[1] = x;
  for (l = 1; l < lmax; ++l)
  {
    p[l+1] = ((2.*l+1.)*x*p[l]-l*p[l-1])/(l+1.);
  }
 //printf("cost = %E, l = %i, Pl = %E\n", x, lmax, p[lmax]);
  return p[lmax];
}


double cached_P_l(double x,
                                int l
                                ) {
  gchar *key;
  gchar *value;
  key = g_new (gchar, 1);
  value = g_new (gchar, 1);
  double answer;
  sprintf(key,"%d %i", x,l);
    if(g_hash_table_lookup(table, g_strdup (key)) == NULL){

    answer = P_l(x,l);
        printf("NOT FOUND IN LIST \n");
    sprintf(value, "%f", answer);
    g_hash_table_insert (table, g_strdup (key), g_strdup (value));
    }
    else{
        printf("FOUND IN LIST \n");
        printf("VALUE: %f \n",atof(g_hash_table_lookup(table, g_strdup (key))));

}
}

int main(){

  GHashTable* table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

  double x=1.;
  int l =2;
  cached_P_l(x,l);
  l=3;
  cached_P_l(x,l);
  cached_P_l(x,l);

  return 0;
}

代码编译得很好,但是当我运行代码时,我得到以下神秘的(至少对我来说)错误:

(process:32996): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed
NOT FOUND IN LIST 

(process:32996): GLib-CRITICAL **: g_hash_table_insert_internal: assertion 'hash_table != NULL' failed

(process:32996): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed
NOT FOUND IN LIST 

(process:32996): GLib-CRITICAL **: g_hash_table_insert_internal: assertion 'hash_table != NULL' failed

0 个答案:

没有答案