Excuse me if this has already been discussed to death but I cannot seem to find anything that relates to the issue I am having. In the code below I am trying to create an array of structures that will be passed along to many different functions. I need to dynamically allocate the array as it varies based on the number of instructions the user inputs. I am not sure if my declaration of the variable of my use of malloc() is incorrect but on every run I experience a break point on the free(instruction) line. I have also tried placing the free(instruction) line outside of the if statement but it yields the same result.This is a homework assignment and any hints or explanation will be greatly appreciated.
struct instructions
{
char destination_register[3],
reg1[3],
reg2[3]; //declaration of destination and source registers.
int delay;
};
struct instructions* instruction;
int main() {
int input=0;
char test1[2];
int test,numberofinstructions=0;
do {
printf ("Pipelined instruction performance\n"
"1) Enter instructions\n"
"2) Determine when instructions are fetched\n"
"3) Exit\n"
"Enter selection : ");
scanf("%d",&input);
if (input==1) {
printf ("Enter number of instructions: ");
scanf ("%d", &numberofinstructions);
instruction = (struct instructions*) malloc(numberofinstructions +
1 * sizeof(struct instructions));
enterinstructs (instruction, numberofinstructions);
printf("\n");
free (instruction);
}
} while (input != 3);
return 1;
}
I don't think that you want to this:
instruction = (struct instructions*) malloc(numberofinstructions + 1 * sizeof(struct instructions));
Here what happened is you allocated space sizeof(struct instructions)
+ numberofinstructions
Which is meaningless.
What you want to do is probably:
instruction = (struct instructions*) malloc((numberofinstructions + 1) * sizeof(struct instructions));