我試圖創建兩個列表,優點和缺點,然後打印出來。 但我無法弄清楚我做錯了什麼。動態分配內存結構c
我試圖用gdb在線調試程序,我發現錯誤在函數fgets()中。
#include <stdio.h>
#include <string.h>
typedef struct list{
char ** reason;
} list;
void printMenu();
void printList(list * myList, int len1);
int main(void)
{
int keepGoing = 0;
int choice = 0;
int i = 0;
int j = 0;
list * pros;
list * cons;
while (!keepGoing){
printMenu();
scanf("%d", &choice);
pros = (list*)malloc(sizeof(list));
cons = (list*)malloc(sizeof(list));
switch (choice){
case 1:
i++;
printf("Enter a reason to add to list PRO: ");
pros = (list*)realloc(pros, i*sizeof(list));
fgets(pros->reason[i], 50, stdin);
pros->reason[strcspn(pros->reason[i], "\n")] = 0;
break;
case 2:
j++;
cons = (list*)realloc(cons->reason, j*sizeof(list));
printf("Enter a reason to add to list CON: ");
fgets(cons->reason[j], 50, stdin);
cons->reason[strcspn(cons->reason[j], "\n")] = 0;
break;
case 3:
printf("PROS:\n");
printList(pros, i);
printf("CONS:\n");
printList(cons, j);
break;
case 4:
keepGoing = 1;
break;
default:
printf("Invalid value.");
keepGoing = 1;
}
}
free(pros);
free(cons);
getchar();
return 0;
}
void printList(list * reasons, int len1){
int i = 0;
for (i = 0; i < len1; i++){
printf("%s\n", reasons->reason[i]);
}
}
void printMenu(){
printf("Choose option:\n");
printf("1 - Add PRO reason\n");
printf("2 - Add CON reason\n");
printf("3 - Print reasons\n");
printf("4 - Exit\n");
}
是什麼'count'? –
[請參閱此討論,爲什麼不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
那麼你'malloc'每個循環的結構...因此每個循環擦除數據。你還可以在以前從未分配過的東西上使用'realloc' [即使'realloc會分配大小,你應該使用'malloc']。阿洛斯'keepGoing'總是等於1;你有一個無限循環;然後你永遠不會釋放它[你忘了釋放列表] – kaldoran