I am new to C and this is my first post here.
My attempts to fix this bug, and other bugs I had, have left this code scrambled, so do keep that in mind. My program reads from the user a complex number and, depending on the command, stores it, or prints it, in one of six typedefed complex struct {double d1, d2; char *val;}
globally-declared vars (A
to F
).
GDB leads me to the free at the bottom and from what I've seen it sometimes frees the input and sometimes it doesn't, for some odd reason it also depends what var I select as the example below shows. Note that remove_space_tab
is of void
type and modifies the original user input from the address malloc
returned. It's probably a silly beginner's mistake, something with the memory I guess.
:
read_comp A, 2.56, -1.32
0x908f068 read_compA,2.56,-1.32
0x908f008 0.00+0.00i // this 4 lines are from printf's that extend to readComp function
0x908f008 //
0x908f008 //
0x908f008 2.56+(-1.32)i //
0x908f068 read_compA,2.56,-1.32
(nil) (null)
Enter a command:
read_comp F, 5.61, -7.56
0x908f068 read_compF,5.61,-7.56
0x908f058 0.00+0.00i //
0x908f058 //
0x908f058 //
0x908f058 5.61+(-7.56)i // F does free the initialised val and sets the user input as the new val
0x908f068 read_compF,5.61,-7.56 // doesn't free this
*** glibc detected *** ./mycomp: double free or corruption (!prev):
0x0908f068
int main() {
A.d1 = 0;
A.d2 = 0;
B.d1 = 0;
B.d2 = 0;
C.d1 = 0;
C.d2 = 0;
D.d1 = 0;
D.d2 = 0;
E.d1 = 0;
E.d2 = 0;
F.d1 = 0;
F.d2 = 0;
A.val = (char*) malloc(12 * sizeof(char));
B.val = (char*) malloc(12 * sizeof(char));
C.val = (char*) malloc(12 * sizeof(char));
D.val = (char*) malloc(12 * sizeof(char));
E.val = (char*) malloc(12 * sizeof(char));
F.val = (char*) malloc(12 * sizeof(char));
sprintf(A.val, "%.2lf+%.2lfi", A.d1, A.d2);
sprintf(B.val, "%.2lf+%.2lfi", B.d1, B.d2);
sprintf(C.val, "%.2lf+%.2lfi", C.d1, C.d2);
sprintf(D.val, "%.2lf+%.2lfi", D.d1, D.d2);
sprintf(E.val, "%.2lf+%.2lfi", E.d1, E.d2);
sprintf(F.val, "%.2lf+%.2lfi", F.d1, F.d2);
while (1) {
input = malloc(30 * sizeof(char));
printf("\nEnter a command:\n");
gets(input);
remove_space_tab(input);
printf("\n%p %s\n", input, input);
if (strncmp(input, "stop", 4) == 0 && *(input + 4) == '\0') {
break;
} else if (strncmp(input, "stop", 4) == 0 && *(input + 4) != '\0') {
printf("Extraneous text after end of command.");
break;
}
if (strncmp(input, "read_comp", 9) == 0) {
input += 9;
readComp(input);
input -= 9;
}
if (strncmp(input, "print_comp", 10) == 0) {
if (!('A' <= *(input + 10) && 'F' >= *(input + 10))) {
printf("\nUndefined complex variable.\n");
break;
}
if (*(input + 11) != '\0') {
printf("\nExtraneous text after end of command.\n");
break;
}
printComp(input[10]);
}
printf("\n%p %s\n", input, input);
free(input);
input = NULL;
if (input != NULL) {
printf("Memory could not be allocated.");
break;
}
printf("\n%p %s\n", input, input);
}
return 0;
}