Yes, you are right! I knew the code were problemtic; just confused why it could possibly work. I actually used flag -O0. It seems gcc still did something behind the scene.
A slightly modified code did not work as expected:
./tmpmain
Segmentation fault (core dumped)
Code:
#include "tmp1.h"
atable *atable_new(char *key1, char *value1, char* key2, char *value2){
GHashTable *table;
table = g_hash_table_new(g_str_hash, g_str_equal);
int i;
g_hash_table_insert(table, (gpointer)key1, (gpointer)value1);
g_hash_table_insert(table, (gpointer)key2, (gpointer)value2);
return (atable *)table;
}
void atable_free(atable *table){
g_hash_table_destroy((GHashTable *)table);
}
gchar *atable_lookup(atable* table, gpointer key){
return (gchar *) g_hash_table_lookup((GHashTable *)table, (gpointer)key);
}
Code:
//tmp1.h
#ifndef _TMP1_
#define _TMP1_
#include <glib.h>
#include <gtk/gtk.h>
typedef void atable;
atable *atable_new();
void atable_free(atable *table);
gchar *atable_lookup(atable* table, gpointer key);
#endif
Code:
#include <stdio.h>
#include "tmp1.h"
int main(int argc, char **argv){
atable *table;
table = atable_new(argv[1], argv[2], argv[3], argv[4]);
printf("%s\n", atable_lookup(table, "sam"));
printf("%s\n", atable_lookup(table, "jack"));
atable_free(table);
}