I am doing an assignment, and I thought i should use a linked list to store some data. The problem is that the list doesn't retain all nodes.
When adding finishes and I try to see the nodes, it only shows the last node that was added to list.
I will write the relevant part below, I hope someone could point out what the problem is.( I suspect that it must be something related to malloc. the address gets destroyed after the functions finishes its work, but am not sure.
Also I should point out, that I tested, printing data while they were being added, and it did show that they were being added properly to the list).
/**
* Adds command name and it's hash onto the linked list
* returns 1, if successful
* returns 0, if failed
*/
int addToList(struct CMDList *head, char *pathCommand[], char *hash){
int result = 0;
/** If head was pointing to NULL, list empty, add at the beginning */
if(head->path == NULL){
head->path = pathCommand[0];
head->command = pathCommand[1];
head->hash = hash;
head->next = NULL;
result = 1;
}else{
struct CMDList *current = head;
/** Find tail of the list */
while(current->next != NULL){
current = current->next;
}
current->next = (struct CMDList *)malloc(sizeof(struct CMDList));
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
}
return result;
}
MAIN Program:
int main(int argc, char *argv[]){
/** CODE DELETED */
/** initialize list for storing cmds from config file */
/** cmdList is the head node that i use to traverse the list */
cmdList = (struct CMDList *)malloc(sizeof(struct CMDList));
if(cmdList != NULL){
cmdList->path = NULL;
cmdList->command = NULL;
cmdList->hash = NULL;
cmdList->next = NULL;
}else{
printError("Silent Exit: couldn't initialize list to store commands of config file");
exit(1);
}
/** CODE DELETED **/
/** add new data to the list */
if(!addToList(cmdList,arrayCommand,sha)){
printError("Silent Exit: couldn't add to list");
exit(1);
}
}