I followed a quite straight forward pseudo code for implementing a linked list of a struct in c, here it is: pseudo code for struct linked list
The problem i am facing is memory loss after adding the 4th node: After the 4th addition, the 4th node points to the 3rd node, which points to a weird address. prior to the 4th addition, the 3rd node pointed to the 2nd node - how did i lose the memory? here's my code:
RailPart *headPart = NULL;
void createRailPart(char *partInfo, char *connectTypes){
char sPart[1];
char ePart[1];
char len[MAX_FIELD_SIZE];
char price[MAX_FIELD_SIZE];
char *noneDigit;
//allocate memory
RailPart *toPush = (RailPart*)malloc(sizeof(headPart));
if (toPush == NULL){
return;
}
//initialize data
sscanf(partInfo, "%[^,],%[^,],%[^,],%[^,]", sPart, ePart, len, price);
(*toPush).start = sPart[0];
(*toPush).end = ePart[0];
for (int i = 0; i < (int) strlen(connectTypes); i++){
if ((toPush)->end == connectTypes[i]){
(toPush)->ePartIdx = i;
}
if ((toPush)->start == connectTypes[i]){
(toPush)->sPartIdx = i;
}
}
(*toPush).len = (int) strtol(len, &noneDigit, BASE_10);
(*toPush).price = (int) strtol(price, &noneDigit, BASE_10);
//push the new node
toPush->nextPart = headPart;
headPart = toPush;
}
here's a documentation of the debugger, showing the memory loss i described clear & informative debugger overview Why am i losing this memory if i allocated it in the heap? what should i do in order to handle the behavior?
Edit: issue fixed, but now i encounter a circle in my linked list - It seems that the computer doesn't remember it already allocated certain parts of the memory and it allocates it again. as you can see, at the 4th iteration, a not in use memory is being allocated, but after reading the sscanf line it changes it's address. how is this possible?