This isn't going to turn into a giant debugging session, but this is a fundamental problem in your code and has to be resolved before anything else.
void init(Instruction head) // note: passed by-value
{
head = (Instruction) malloc(sizeof(struct Command));
// etc...
}
Consider this: Take a function that you want to use to set a caller-side int
variable to some value. You'd do it like this:
void func(int *p) // note by-address
{
*p = 42;
}
// caller code
int a = 0;
func(&a); // pass address
Pointers are no different. Pointers hold addresses, but the also have addresses (this distinguishes them from arrays, btw, which simply are addresses). Your init()
should look like this:
void init(Instruction* head) // note: by address
{
Instruction p = malloc(sizeof(struct Command)); // note no cast
p->->opcode = 0;
p->next = NULL;
// etc...
// save result to address given by out-parameter
*head = p;
}
Caller side:
Instruction head = NULL;
init(&head); // note address passed.
This should get you going.
Side Note
C programmers like asterisks. Really. Not kidding. They're giant flags in the code that scream from the mountain-tops "THIS IS A POINTER". Hiding that in a typedef
is rarely helpful. In fact there are only three cases I've seen where they are arguably legitimate, and one of those is a red-herring.
- An abtract opaque "handle" type for a library API. This is common and completely legitimate.
- Function pointer types. Often used to ensure proper types are being used for different "callback" mechanisms (
typedef int (*callback_type)(void);
for example). - Avoiding incorrect variable declarations on the same line. (this is the red herring).
The third of those is best demonstrated:
int* a,b; // declares one pointer-to-int, one int.
typedef int *int_ptr;
int_ptr a,b; // declared two pointers-to-int.
While that may seem helpful, it really isn't. The compiler will bomb when you try this later in the code:
*b = something;
So you'll catch yourself regardless (usually).
Bottom line, don't be afraid of asterisks. They're there to help you see things clearer if you let them.