Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using malloc in C to allocate space for a typedef'd type

I'm not sure exactly what I need to use as an argument to malloc to allocate space in the table_allocate(int) function. I was thinking just count_table* cTable = malloc(sizeof(count_table*)), but that doesn't do anything with the size parameter. Am I supposed to allocate space for the list_node_t also? Below is what I am working with.

In the .h file I'm given this signature:

//create a count table struct and allocate space for it                         
//return it as a pointer                                                        
count_table_t* table_allocate(int);

Here are the structs that I'm supposed to use:

typedef struct list_node list_node_t;

struct list_node {
  char *key;
  int value;

  //the next node in the list                                                   
  list_node_t *next;
};

typedef struct count_table count_table_t;

struct count_table {
  int size;
  //an array of list_node pointers                                              
  list_node_t **list_array;
};
like image 471
user516888 Avatar asked Oct 16 '25 23:10

user516888


1 Answers

count_table* cTable = malloc(sizeof(count_table*))

is wrong. It should be

count_table* cTable = malloc(sizeof(count_table));

Also, you must allocate memory for list_node_t also seperately.

EDIT:

Apart from what Clifford has pointed about allocating memory for the list node, I think the memory allocation should also be taken care for the char *key inside of the list node.

like image 195
Jay Avatar answered Oct 18 '25 17:10

Jay