[問題] linked-list 與free()

看板C_and_CPP (C/C++)作者 (嗨~)時間13年前 (2012/11/10 22:31), 編輯推噓0(009)
留言9則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC,Dev C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) string.h 問題(Question): 宣告的部份: #define MAX 10; struct Node { char a[MAX]; char b[MAX]; char c[MAX]; char d[MAX]; struct Node *next; }; typedef struct Node * DATA; 程式的部份 char ch; char str *; DATA new_record; do { fflush(stdin); new_record=(DATA)malloc(sizeof(DATA)); str=(char *)malloc(MAX*sizeof(char)); printf("請輸入a,Enter結束:"); scanf("%s",str); strcpy(new_record->a,str); scanf("%c",&ch); /* 讀取 Enter */ free(str); str=(char *)malloc(MAX*sizeof(char)); printf("請輸入b,ENTER結束:"); scanf("%s",str); strcpy(new_record->b,str); scanf("%c",&ch); /* 讀取 Enter */ free(str); 同上,輸入c,d~ new_record->next=first; first=new_record; }while(1); 當我第一次輸入資料的時候 是可以正確讀取到的 但是之後只要在輸入資料 前面節點的值,有些就會亂掉(不是全部) 用Dev C++開的話,利用軟體的除錯功能 會在free(str);這行卡住 CPU使用率會100% 可是, 我用監看變數去看 *new_record 內容顯示會正確的, 直到某一行的free(str) 他之前存的內容會改變 = = 好奇怪@@ 為什麼已存入的值會因為釋放記憶體改變... 餵入的資料(Input): 第一次 1111 111 11 1 第二次 2222 222 22 2 第三次 3333 33333 333333 3333333 預期的正確結果(Expected Output): 3333 33333 333333 3333333 (...其它printf) 2222 222 22 2 (~) 1111 111 11 1 錯誤結果(Wrong Output): 3333 33333 333333333333 3333333 (~~) 22223333 222 22 33333333333 (~~) 111122223333 33 11 2 程式碼(Code):(請善用置底文網頁, 記得排版) http://ideone.com/FBuHWc 補充說明(Supplement): 感謝你~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.225.45 ※ 編輯: fgwilliam 來自: 140.123.225.45 (11/10 22:33) ※ 編輯: fgwilliam 來自: 140.123.225.45 (11/10 22:33) ※ 編輯: fgwilliam 來自: 140.123.225.45 (11/10 23:13)

11/10 23:18, , 1F
既然DATA是pointer 那你只有alloc 4bytes 是嗎0.0
11/10 23:18, 1F

11/10 23:18, , 2F
為什麼複製到網站上會有錯誤= =
11/10 23:18, 2F

11/10 23:20, , 3F
不懂耶@@ 我第一次用linked list
11/10 23:20, 3F

11/10 23:24, , 4F
你是說因為只有4bytes 可是我宣告的有4*MAX超過嗎?
11/10 23:24, 4F

11/10 23:48, , 5F
new_record=(DATA)malloc(sizeof(DATA));總覺得這行會錯
11/10 23:48, 5F

11/10 23:51, , 6F
sizeof(DATA) = 8 byte 給 new_record 夠用嗎?
11/10 23:51, 6F

11/11 00:12, , 7F
以前完全忽略指標只有4bytes =口=!
11/11 00:12, 7F

11/11 00:13, , 8F
那為什麼GCC不會警告這個問題,反而網站上會@@?
11/11 00:13, 8F

11/13 22:52, , 9F
new_record=(DATA)malloc(sizeof(struct Node)); ...
11/13 22:52, 9F
文章代碼(AID): #1GdcKnd1 (C_and_CPP)
文章代碼(AID): #1GdcKnd1 (C_and_CPP)