[問題] free會出現錯誤

看板C_and_CPP作者 (臨玥)時間15年前 (2010/04/17 23:25), 編輯推噓5(5015)
留言20則, 6人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 寫matrix的相關運算 在free的時候似乎會出現錯誤 有試過逐行printf 錯在freeMatrix的free(x->data); 可是不清楚自己錯在哪 希望得到的正確結果: free正確,程式可以執行 程式跑出來的錯誤結果: 程式發生問題,必須關閉 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Dev-C++ 有問題的code: (請善用置底文標色功能) 因為算是大程式 只節錄部份程式碼:http://paste.plurk.com/show/233782/ typedef struct matrix { int row, col; int* data; } *MATRIX; VMatrix[7]; MATRIX newMatrix(int row, int col) { // 產生新矩陣所需的記憶體空間 MATRIX m; if ( (m = (MATRIX) malloc(sizeof(MATRIX))) == NULL ) { printf("Function newMatrix(): malloc error!\n"); return NULL; } m->row = row; m->col = col; // 產生存放資料所需的空間 if ( ( m->data = (int*)malloc(m->row*m->col*sizeof(int))) == NULL ) { printf("Function newMatrix(): m->data malloc error!\n"); return NULL; } return m; } int readMatrix() { int matrix_num; int matrix_row; int matrix_col; MATRIX m; //讀檔input.txt if( ( myfile = fopen("input.txt","r") ) == NULL ) { printf("File cannot be opened\n"); return (-1); } for ( int i = 0; i < 7; i++ ) { fscanf(myfile, "%d %d %d\n", &matrix_num, &matrix_row, &matrix_col); if ( (matrix_row < 1) || (matrix_col < 1) ) { printf("matrix error!!\n"); } m = newMatrix(matrix_row, matrix_col); for ( int i = 0; i < matrix_row; i++ ) { for ( int j = 0; j < matrix_col; j++ ) { fscanf( myfile, "%d", m->data+i*matrix_col+j ); } } VMatrix[matrix_num] = m; } //將動態分配矩陣的空間還給系統 void freeMatrix(MATRIX x) { free(x->data); free(x); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.47.70.192

04/17 23:30, , 1F
m = (MATRIX) malloc(sizeof(MATRIX)))
04/17 23:30, 1F

04/17 23:30, , 2F
這樣的大小應該是一個pointer,而不是struct matrix
04/17 23:30, 2F

04/17 23:32, , 3F
不知道你的 freeMatrix 是在哪裡被呼叫的...?
04/17 23:32, 3F

04/17 23:32, , 4F
對耶 一樓提的那個問題也很嚴重
04/17 23:32, 4F

04/17 23:33, , 5F
我是建議不要把指標typedef成一個型別,容易寫錯...
04/17 23:33, 5F

04/17 23:34, , 6F
不知道為什麼很多書都喜歡把指標做 typedef...
04/17 23:34, 6F

04/17 23:47, , 7F
我耍笨了 的確是一樓提的問題 謝謝
04/17 23:47, 7F

04/17 23:47, , 8F
typedef是為了方便起見吧
04/17 23:47, 8F

04/17 23:54, , 9F
個人覺得一點都不方便 XD 好混亂 (大概是我比較笨吧...)
04/17 23:54, 9F

04/18 00:03, , 10F
typedef 寫的人方便, 看的人痛苦
04/18 00:03, 10F

04/18 00:16, , 11F
因為typedef指標後, 就可以寫LPDWORD p1, p2, p3; 這樣
04/18 00:16, 11F

04/18 00:17, , 12F
宣告三個指標, 不用DWORD *p1, *p2, *p3; 更不用擔心寫
04/18 00:17, 12F

04/18 00:17, , 13F
成DWORD* p1, p2, p3; 這種意料之外的宣告吧@_@"
04/18 00:17, 13F

04/18 00:17, , 14F
不方便+1 不過如果定的名字顯示出它是指標(像樓上的LPDWORD)
04/18 00:17, 14F

04/18 00:17, , 15F
那我可接受
04/18 00:17, 15F

04/18 00:18, , 16F
我是 *p1,*p2,*p3; 派的耶 XD
04/18 00:18, 16F

04/18 00:19, , 17F
小弟我也是 *pvar 派, 而不習慣 TYPE* 這樣....XD
04/18 00:19, 17F

04/18 01:40, , 18F
如果名字裡有個 P 來說明是指標的話就還好
04/18 01:40, 18F

04/18 01:40, , 19F
原 PO 的 matrix 與 MATRIX 這樣真的會很亂啊...
04/18 01:40, 19F

04/18 12:02, , 20F
對啊, 所以原po就亂掉啦XDDD
04/18 12:02, 20F
文章代碼(AID): #1BoTBYwp (C_and_CPP)