[問題] free會出現錯誤
遇到的問題: (題意請描述清楚)
寫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
04/17 23:30, 1F
→
04/17 23:30, , 2F
04/17 23:30, 2F
→
04/17 23:32, , 3F
04/17 23:32, 3F
→
04/17 23:32, , 4F
04/17 23:32, 4F
→
04/17 23:33, , 5F
04/17 23:33, 5F
→
04/17 23:34, , 6F
04/17 23:34, 6F
→
04/17 23:47, , 7F
04/17 23:47, 7F
→
04/17 23:47, , 8F
04/17 23:47, 8F
→
04/17 23:54, , 9F
04/17 23:54, 9F
推
04/18 00:03, , 10F
04/18 00:03, 10F
推
04/18 00:16, , 11F
04/18 00:16, 11F
→
04/18 00:17, , 12F
04/18 00:17, 12F
→
04/18 00:17, , 13F
04/18 00:17, 13F
推
04/18 00:17, , 14F
04/18 00:17, 14F
→
04/18 00:17, , 15F
04/18 00:17, 15F
→
04/18 00:18, , 16F
04/18 00:18, 16F
→
04/18 00:19, , 17F
04/18 00:19, 17F
→
04/18 01:40, , 18F
04/18 01:40, 18F
→
04/18 01:40, , 19F
04/18 01:40, 19F
推
04/18 12:02, , 20F
04/18 12:02, 20F