Allocating Array of Pointers to Struct Nodes Causing Crash?

  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Array Pointers
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 3K views
camel-man
Messages
76
Reaction score
0
I need some help with this piece of code I wrote earlier, it is compiling correctly but when I try to use my tester program it crashes.


I am trying to create an array of pointers to struct Nodes
Code:
typedef struct Node *NodeP;

struct Node
{
	NodeP next;
	EmployeeP info;	
};


struct EmployeeList
{
	NodeP* root;
	int size;
};


EmployeeListP newEmployeeList(int size)
{
	//Creating employeelist and allocating memory for the array or pointers to nodes
	EmployeeListP e=malloc(sizeof(struct EmployeeList));
	e->root=malloc(sizeof(NodeP)* (size*2));
	int i;
	if(e==NULL || e->root==NULL)
	{
		fprintf(stderr,"Failed to allocate memory!\n");
		exit(1);
	}
	//Initializing list size and all pointers to NULL
	e->size=size;
	for(i=0;i<size*2;i++)
	{
		e->root[i]->info=NULL;
		e->root[i]->next=NULL;
	}

	return e;

}


test program where it crashes
Code:
#include <stdio.h>
#include <stdlib.h>
#include"Employee.h"
#include"EmployeeList.h"

int main(void)
{
	EmployeeListP e= newEmployeeList(10);

	return 0;
}
 
Physics news on Phys.org
This line in your newEmployeeList function looks suspect to me.
Code:
e->root=malloc(sizeof(NodeP)* (size*2));
What's the purpose of 2 in the line above?
Also, I think you should cast the value returned by malloc as NodeP.
 
I have to make the array twice the size of the parameter passed in by the user. I am creating a hash table program and that is one of the specifications.
 
During initialization, you haven't allocated any nodes for e->root to use, only the pointers, so all you can do at this point is:

Code:
    for(i=0;i<size*2;i++)
    {
        e->root[i] = NULL;
    }

or you could allocate nodes:

Code:
    for(i = 0; i < size*2; i++)
    {
        e->root[i] = (NodeP) malloc(sizeof(Node));
        e->root[i]->info = NULL;
        e->root[i]->next = NULL;
    }