Start New Discussion within our Software Development Community

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

#define MAX 10

typedef struct{
    char elem;
    int next;

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

void initList(virtualHeap *);
int initVirtualHeap(virtualHeap *);
void insertValues(virtualHeap *, List*);
void insertSortedUnique(virtualHeap *, List, char);
int main()
    virtualHeap *A;
    List B;
    insertValues(A, &B);
    return 0;
void initList(virtualHeap *V)
    V=(virtualHeap *)malloc(sizeof(virtualHeap));
    V->nodes=(vArray *)malloc(sizeof(vArray)*MAX);
int initVirtualHeap(virtualHeap *V)
     int p;
     for (p=0;p<MAX;p++){
     return p;
void insertValues(virtualHeap *V, List *A)
    int p, temp;
    for (p=*A;p!=-1;p=V->nodes[p].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.

Great explanation! Again.
This question has already been answered. Start a new discussion instead.