create_entry(strdup(word), strdup(desc))
Using strings from a text file is working different than using literal strings?
سؤال
I have a C program that is reading strings from a text file and using these to create structs which are being placed in a hash table (d_table). It reads from a file line by line in a loop. The runtime problem I get is that every entry added using strings taken from a file all seem to still be pointing to whatever was most recently read (so char word[] would just be "."), BUT if it was to hard code in some entries (like the second ht_insert) then it works fully as expected. This makes me think that I am missing something obvious in how C handles strings...
A line of the text file looks like: "Test This is a test line", with the last line being a "."
entry struct:
struct d_entry {
char *word;
char *desc;
};
I don't think the problem is caused at create_entry or beyond in the program, otherwise why would hard coded entries work perfectly fine? As far as I know, beyond this point entries should be indistinguishable whether the strings were hard coded or taken from a file:
struct d_entry * create_entry(char *word, char*desc) {
struct d_entry * e;
e = (struct d_entry *) malloc(sizeof(struct d_entry));
e->word = word;
e->desc = desc;
return e;
}
This is the necessary code taken from the function reading from file. I have tested plenty and the file handling and the extracting of strings from files seems to be working correctly: The first ht_insert call causes the runtime problem, the second call is an example of hard coding an entry which works perfectly correctly:
int read_from_file(const char * filename) {
char word[40];
char desc[200];
FILE * fp;
fp = fopen(filename, "r");
fscanf(fp, "%s %[^\n]]", word, desc);
while (word[0] != '.') {
ht_insert (d_table, create_entry(word, desc)):
ht_insert (d_table, create_entry("test", "test desc"));
fscanf(fp, "%s %[^\n]", word, desc);
}
fclose(fp);
return 1;
}
Any help would be greatly appreciated, thanks.
المحلول
نصائح أخرى
Use strdup
to make a heap copy of each string you store in your data structure.
Do that for both strings read from file (into temp buffer) and static strings.