Can somebody please tell me what im doing wrong, I know its the initVirtualHeap but i dont know why. The program just crashes.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10

typedef struct{
    char elem;
    int next;
}vArray;

typedef struct{
    vArray *nodes;
    int avail;
}virtualHeap;
typedef int List;

void initList(virtualHeap *);
int initVirtualHeap(virtualHeap *);
void insertValues(virtualHeap *, List*);
void insertSortedUnique(virtualHeap *, List, char);
int main()
{
    virtualHeap *A;
    List B;
    initList(A);
    B=initVirtualHeap(A);
    insertValues(A, &B);
    getch();
    return 0;
}
void initList(virtualHeap *V)
{
    V=(virtualHeap *)malloc(sizeof(virtualHeap));
    V->nodes=(vArray *)malloc(sizeof(vArray)*MAX);
    V->avail=-1;
}
int initVirtualHeap(virtualHeap *V)
{
     int p;
     for (p=0;p<MAX;p++){
        V->nodes[p].next=p-1;
     }
     V->avail=MAX-1;
     p=V->avail;
     return p;
}
void insertValues(virtualHeap *V, List *A)
{
    int p, temp;
    for (p=*A;p!=-1;p=V->nodes[p].next){
        temp=V->avail;
        if(temp!=-1){
            V->avail=V->nodes[temp].next;
        }
        printf("Enter character: ");
        scanf("%c", &V->nodes[p].elem);
    }
}

On line 23 you create a pointer. It is pointing at some random memory somewhere.

On line 25, you pass a COPY of that pointer to the function initList ("pass by value" is the name for this - the function initList gets a copy of the parameter). This function uses malloc to allocate that memory, and changes its COPY of the pointer to point at that memory. When the function ends, the copy is thrown away and you have no way of accessing that memory you allocated.

The original, named A, has not changed. It is still pointing at some random memory somewhere.

On line 26, you pass another copy of A to the function initVirtualHeap. Because A never changed, it is still pointing at some random memory somewhere. You then start trying to write into that random memory. This is very bad and the OS stops you.

commented: Great explanation! Again. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.