0

This is relatively confusing as the code was just working. I have a linked list stack that uses malloc and free. They were working just fine up until a made a few changes to my main program that calls the stack, no changes were made on how the stack was called.

#include <stdio.h>
#include <stdlib.h>

#define null (void *)0

// LINKED LIST NODE -----------------------------------------------
// ================================================================

// Linked list node
struct Node {
    double value;
    struct Node *next;
};


// GLOBAL VARIABLES -----------------------------------------------
// ================================================================

// first node (global variable)
struct Node *first = null;


// STACK FUNCTIONS ------------------------------------------------
// ================================================================

// Push function
void push(double x){
    struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));

    temp->value = x;
    temp->next = first;
    first = temp;
}

// ----------------------------------------------------------------

// Pop function
double pop(){
    struct Node *temp;

    if (first == null){
        return 0;
    }

    temp = first;
    double x = temp->value;
    first = first->next;
    free(temp);

    return x;
}

// ----------------------------------------------------------------

// Peek function
double peek(){
    double x = pop();
    push(x);
    return x;
}

It is in the pop function where free() is located and where it is crashing. The main function that is calling it has an if statement that looks like this:

// routine that gets userInput
// if userInput is a number, keep adding to variable data
// else if userInput is a command, copy to operator

strcpy(operator, userInput);
data = 0;

// routine to get new userInput and data
// if userInput is a command move to if statements below

if(strcmp(operator, "+") == 0){
    push(pop() + data);
    data = 0;
    printf("   %f\n", peek());
    strcpy(operator, userInput);
}

It is during the execution of free() in the stack that I am getting a "No source available for "ntdll!RtlpNtEnumerateSubKey() at 0x77cf04e5" error.

Also the console is outputting this:

warning: Heap block at 00931888 modified at 00931894 past requested size of 4

TheWinterSnow
  • 175
  • 11

1 Answers1

0

The line:

struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));

allocates the wrong amount of memory for temp. It should be:

struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
                                             // Remove the pointer 

As a rule of thumb, use the following pattern:

type* var = malloc(sizeof(*var));

In your case, it would be:

struct Node *temp = malloc(sizeof(*temp));

Also, read on why you should not cast the return value of malloc.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270