Solution: Allocated memory is freed up after a program exits. Have to read+write from disk back into a linked list, and then rewrite to update the database! Thank you everyone =)
Hello, I've basically been working on this database program for the past few nights but I just continuously reach dead ends. The assignment is due today so if you could help me out, it would be very much appreciated. =T
The database is implemented with a Linked List and consists of a few files: sdbm.c, sdbm.h, new.c, get.c, insert.c, put.c, and remove.c. sdbm.c holds the methods for the database based on the sdbm.h interface, and the other files contain main methods that use the methods from sdbm.
The first problem comes with the insert program, which seems to work fine when I try to add in a key and value pair ... that is, until we try to call the insert program again. The memory allocated seems to have disappeared! I've been researching, trying to figure out why even though I have malloced, why does it disappear after the insert program exits. Here is some code:
- The node structure + global variable:
struct dbase_Node {
char *keyValue;
char *element;
struct dbase_Node *next;
};
typedef struct dbase_Node Node;
Node *head;
========
- The insert method
static bool sdbm_insert_back(Node **headRef, const char *key, const char *value)
{
Node *new = (Node *)malloc(sizeof(Node));
if (new == NULL)
return false;
else {
new->keyValue = malloc(strlen(key));
new->element = malloc(strlen(value));
strcpy(new->keyValue, key);
strcpy(new->element, value);
new->next = *headRef;
*headRef = new;
return true;
}
}
- The sync method
bool sdbm_sync()
{
if (!isOpen()) { return false; }
if (fopen(databaseName, "w" ) == NULL) {
error = SDBM_FOPEN_FAILED;
return false;
}
Node *current = head;
while (current != NULL) {
fprintf(database, "Key: %s\n", current->keyValue);
fprintf(database, "Value: %s\n", current->element);
current = current->next;
}
return true;
}
I run the following:
./new [database] <-- works fine ./insert [database] [key] [value] <--seems to work fine
And then after I try to insert more, the already added nodes have disappeared ...