I am trying to make a program experimenting with malloc linked lists. I keep getting this error. It says:
Debug Assertion Failed!
Program: ...ource\repos\ConsoleApplication1\Debug\ConsoleApplication1.exe
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
line: 904
Expression: _CrtlsValidHeapPointer(block)
Here is my code:
#include <stdio.h>
#include <corecrt_malloc.h>
#include <cstddef>
struct node_t {
int value;
struct node_t* next;
};
void printList(node_t* headNode) {
node_t* currentNode;
currentNode = headNode;
while ((currentNode->next) != NULL) {
printf("%d, ", currentNode->value);
currentNode = currentNode->next;
}
printf("%d", currentNode->value);
currentNode = currentNode->next;
}
void addNode(node_t* headNode, int nodeValue) {
node_t* currentNode = headNode;
node_t* tempNode = headNode;
while ((currentNode->next) != NULL) {
currentNode = currentNode->next;
tempNode = currentNode;
}
currentNode = (node_t*)(malloc(sizeof(node_t)));
currentNode->value = nodeValue;
tempNode->next = currentNode;
currentNode->next = NULL;
}
void popHead(node_t* headNode) {
node_t* newHead = headNode->next;
free(headNode);
headNode = newHead;
}
void freeAllNodes(node_t* headNode) {
node_t* currentHead;
node_t* tempNode;
currentHead = headNode->next;
free(headNode);
while ((currentHead->next) != NULL) {
tempNode = currentHead;
currentHead = tempNode->next;
free(tempNode);
}
free(currentHead);
}
int main()
{
node_t* nextNode;
node_t* tempNode;
node_t* headNode;
headNode = (node_t*)(malloc(sizeof(node_t)));
headNode->value = 1;
headNode->next = NULL;
printList(headNode);
printf("\n");
addNode(headNode, 2);
printList(headNode);
printf("\n");
addNode(headNode, 3);
printList(headNode);
printf("\n");
popHead(headNode);
freeAllNodes(headNode);
return 0;
}
I believe the problem is in Pop Head
note: The reason i am not using 'new' and 'delete' is because i want to keep it as close to regular c as possible.
headNode = (node_t*)(malloc(sizeof(node_t)));just why ? - Richard CrittenStack Frame(on the toolbar) back to your code to see what was being executed when this happened. - drescherjmnew,delete,std::cout, etc. - 1201ProgramAlarm