0
votes

I am having issues with my code. I am supposed to have 4 files. list.h, listAdders.c, listMovers.c, and listRemovers.c.

I am supposed to statically declare 2 blocks of memory for lists and nodes of sizes minList and minNodes. And Malloc() is only allowed to be used at runtime (which means I am not allocating memory as a per-list or per-node basis).

listRemovers.c and listMovers.c will need access to the memory block I allocate using malloc() for my lists and nodes.

There is no init() function, and I don't know how I can malloc() a global variable array which will hold the Lists and Nodes.

Just in case my question is unclear. How do I malloc an initial block of memory for my struct of lists and nodes? So that when I create a list or add a node, they're stored on the memory I allocated.

Here's what I have:

list.h

#ifndef __LIST__
#define __LIST__

#define MIN_LISTS 3
#define MIN_NODES 30

typedef struct NODE{
    struct NODE* next;
    struct NODE* prev;
} NODE;

typedef struct LIST{
    struct NODE* head;
    struct NODE* cursor;
    int size;
} LIST;

extern NODE *node_block;
extern LIST *list_block;

LIST *ListCreate();

int ListAdd(LIST *list, void* item); 

#endif // __LIST__

listAdders.c

#include "list.h"
#include <stdlib.h>
#include <stdio.h>

NODE *node_block = malloc(MIN_NODES * sizeof(struct NODE));
LIST *list_block = malloc(MIN_LISTS * sizeof(struct LIST));

LIST *ListCreate()
{

}

int ListAdd(LIST * list, void* item)
{

}
1
The list is passed as parameter to any of these functions. Why would you need it global? Also I see no rationale to use dynamic allocation for static variables. - Eugene Sh.
Aren't double underscores reserved for the implementation? - Rorschach

1 Answers

2
votes

There is no init() function, and I don't know how I can malloc() a global variable array which will hold the Lists and Nodes.

C does not allow executable code outside of actual functions.

So this code will not compile:

NODE *node_block = malloc(MIN_NODES * sizeof(struct NODE));
LIST *list_block = malloc(MIN_LISTS * sizeof(struct LIST));

Given your problem statement:

I am supposed to statically declare 2 blocks of memory for lists and nodes of sizes minList and minNodes.

Replacing your code above with this code would be a "static declaration":

NODE node_block[ MIN_NODES ];
LIST list_block[ MIN_LIST ];

You could also do something like this:

NODE *node_block;
LIST *list_block;

static void init_memory()
{
    node_block = malloc(MIN_NODES * sizeof( *node_block ));
    list_block = malloc(MIN_LISTS * sizeof( *list_block ));
}

int main( int argc, char **argv )
{
    init_memory();
      .
      .
      .
}

Note that starting with a fixed number of allocated nodes and lists will result in needlessly complex code should you need more nodes and/or lists than you start out with.

Either statically allocate all of your memory, or dynamically allocate all of it. That way your code will be a lot simpler.