1

I'm trying to create an empty stack but somehow there is an error with the malloc I couldn't figure out even with debbuger.

The message my debbuger shows is:

sysmalloc: Assertion (old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0) failed.
Aborted

How should I fix it?

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

typedef struct
{
    int x;
    int y;
    int r;
    int g;
    int b;
}Pixel;

typedef int TypeKey;

typedef struct {
    TypeKey Key;
    Pixel P;
} TypeItem;

typedef struct Cell_str *Pointer;

typedef struct Cell_str {
    TypeItem Item;
    Pointer Next;
} Cell;

typedef struct {
    Pointer Top, Bottom;
    int Size;
} TypeStack;

void FEmpty(TypeStack *Stack)
{
    Stack->Top = (Pointer)malloc(sizeof(Cell*));
    Stack->Bottom = Stack->Top;
    Stack->Top->Next = NULL;
    Stack->Size = 0;
}

int Empty(const TypeStack *Stack){
    return (Stack->Top == Stack->Bottom);
}

int size(TypeStack Stack)
{
    return (Stack.Size) ;
}


int main(int argc, char *argv[])
{

    Pixel P[500][500];; 


    TypeStack *Stack;
    FEmpty(Stack);


    return 0;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Andre
  • 115
  • 12

1 Answers1

2

1

TypeStack *Stack;
FEmpty(Stack);

Stack is uninitialized - it points to nothing, or garbage.

In FEmpty you immediately dereference the (invalid) pointer, causing undefined behavior.

You need to either allocate the structure using malloc, or simply declare a local variable:

TypeStack Stack;
FEmpty(&Stack);

2

Stack->Top = (Pointer)malloc(sizeof(Cell*));

Next, you don't allocate enough memory here. You're only allocating the size of the pointer itself, and not the structure it points to.

Use this construct to avoid this mistake. And don't cast the result of malloc.

Stack->Top = malloc(sizeof(*Stack->Top));
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328