Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct node {
char* identifier;
char* expression;
struct node* next;
} node;
void add(node** database, char* _identifier, char* _expression, int * size) {
node* tmp = (node*) malloc (sizeof(node));
tmp->identifier = _identifier;
tmp->expression = _expression;
tmp->next = *database;
*database = tmp;
(*size)++;
printf("Added: %s : %s\n", _identifier, _expression); fflush(NULL);
}
void show(node* database, int size) {
if (database == NULL) {
printf("Database empty\n");
}
else {
node* tmp = database;
printf("Identifier list (%d):\n", size); fflush(NULL);
while (tmp != NULL) {
printf("%s : \"%s\" \n", tmp->identifier, tmp->expression);fflush(NULL);
tmp = tmp->next;
}
}
}
int main() {
node* database = NULL;
int size = 0;
add(&database, "a1", "abc", &size);
add(&database, "a2", "def", &size);
add(&database, "a3", "ghi", &size);
char identifier[20];
char expression[1000];
int i;
for (i = 0; i<3; i++) {
scanf("%s %s", identifier, expression);
add(&database, identifier, expression, &size);
}
show(database, size);
printf ("Bye!");
return 0;
}
The “Add” function works well when called manually, but it doesn’t work inside the loop, with data read from stdin. Below is the result from one run:
Added: a1 : abc
Added: a2 : def
Added: a3 : ghi
a4 mno
Added: a4 : mno
a5 ghi
Added: a5 : ghi
a6 kml
Added: a6 : kml
Identifier list (6):
a6 : "kml"
a6 : "kml"
a6 : "kml"
a3 : "ghi"
a2 : "def"
a1 : "abc"
Bye!
As you can see the node a1, a2, a3 were added correctly into the list. However, a4 and a5, after correctly added to the list, were changed to all “a6” after a6 is added.
It took me one day already but I couldn’t figure it out. Anybody?
Your problem is that they are all pointing to the same pointer:
identifier. (alsoexpression). (Whereas the first 3 adds are pointing to separateconst char*s statically initialised.)To resolve this you need to dynamically allocate space for each new element you add (e.g. with
malloc) and release them (e.g. withfree) when you remove them.e.g:
You must ensure that these resources are correspondignly released at some point or you will have a memory leak.