Here is my code for pop:
int pop (struct_of_ints *head_node){
int val;
if (head_node == NULL){
fprintf(stderr, "Empty stack.\n");
return -1;
}
else {
struct_of_ints *curr;
struct_of_ints *prev;
curr = head_node;
prev = NULL;
while (curr->next != NULL) {
prev = curr;
curr = curr->next;
}
val = curr->value;
if (prev == NULL)
head_node = NULL;
else
prev->next = curr->next;
free(curr)
return val;
}
}
When I try to free(curr), however, I get a segmentation fault and when I run valgrind I get messages like "Invalid free() / delete / delete[]", "Address 0x51c1f60 is 16 bytes inside a block of size 32 free'd", and "Invalid read of size 8"...I have no idea what's wrong. If anyone could help I'd appreciate it. Thanks!
You are passing the pointer *head_node, in the function, which is getting passed by value. To update *head_node, try passing **head_node, and change the code as::
int pop (struct_of_ints **head_node)
{
int val;
if (*head_node == NULL)
{
fprintf(stderr, "Empty stack.\n");
return -1;
}
else
{
struct_of_ints *curr;
struct_of_ints *prev;
curr = *head_node;
prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
val = curr->value;
if (prev == NULL)
*head_node = NULL;
else
prev->next = curr->next;
free(curr)
return val;
}
}