2013-10-22 52 views
0

我正在使用code :: blocks。釋放我的矩陣時出現分段錯誤

代碼在dealloc_mat中迭代2-3次後釋放矩陣時發送seg錯誤。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 


int **_mat; 
int _lines, _columns; 


void alloc_mat(); 
void dealloc_mat(); 

int main(int argc, char *argv[]) 
{ 
    _lines = 31, _columns = 22; 

    alloc_mat(); 
    dealloc_mat(); 

    return 0; 
} 

void alloc_mat() 
{ 
    int i, row, col; 
    _mat = malloc(sizeof(int *) * _lines); 

    for(i = 0 ; i < _lines ; i++) 
    { 
     int *tmpMatrix = malloc(sizeof(int) * _columns); 
     _mat[i] = &tmpMatrix[i]; 
    } 

    for(row = 0 ; row < _lines ; row++) 
    { 
     for(col = 0 ; col < _columns ; col++) 
     { 
      _mat[row][col] = 0; 
     } 
    } 
} 

void dealloc_mat() 
{ 
    int row; 

    for(row = 0; row < _lines; row++) 
    { 
     free(_mat[row]); 
    } 

    free(_mat); 
} 
+2

其中是tmpMatrix的定義?此代碼不應編譯 – SheetJS

+0

對不起,已編輯。複製錯誤的樣本。 –

回答

1

這裏的錯誤:

_mat[i] = &tmpMatrix[i]; 

應該

_mat[i] = &tmpMatrix[0]; 

或更好

_mat[i] = tmpMatrix; 
+0

謝謝,我是個傻瓜。 –

0

這裏是用來爲字符串分配內存一對夫婦的功能,字符串數組實際上,你可以很容易地修改他們你的目的:

char **strings; // created with global scope (before main()) 
void allocMemory(int numStrings, int max) 
{ 
    int i; 
    strings = malloc(sizeof(char*)*(numStrings+1)); 
    for(i=0;i<numStrings; i++) 
     strings[i] = malloc(sizeof(char)*max + 1); 
} 

void freeMemory(int numStrings) 
{ 
    int i; 
    for(i=0;i<numStrings; i++) 
     if(strings[i]) free(strings[i]); 
    free(strings); 
} 

下面是上面會被修改(和使用)的整數:(注意,這是真的只是承認差異sizeof(type)
還要注意:使用malloc()不初始化值。如果要確保每個元素的初始值(例如,),則可以改爲使用calloc()

void allocMemoryInt(int rows, int cols); 
void freeMemoryInt(int numStrings); 
int **array; 

int main(void) 
{ 
    allocMemoryInt(10, 3); 
    freeMemoryInt(10); 
    return 0; 
} 

void allocMemoryInt(int rows, int cols) 
{ 
    int i; 
    array = malloc(sizeof(int *)*(rows)); //create memory for row pointers 
    for(i=0;i<rows; i++) 
     array[i] = malloc(sizeof(int)*cols + 1); //create memory for (row * col) elements 
} 

void freeMemoryInt(int rows) 
{ 
    int i; 
    for(i=0;i<rows; i++) 
     if(array[i]) free(array[i]);//call free for each row 
    free(array); //free pointer array(will clean up everything allocated) 
} 
1

的問題是,你不正確分配它。這:

for(i = 0 ; i < _lines ; i++) 
    { 
     int *tmpMatrix = malloc(sizeof(int) * _columns); 
     _mat[i] = &tmpMatrix[i]; 
    } 

應該是這樣的:

for(i = 0 ; i < _lines ; i++) 
    { 
     _mat[i] = malloc(sizeof(int) * _columns); 
    } 

用C此外,_mat_lines_columns是保留的標識符,你不應該使用它們。以普通文件範圍(即_mat)或標記(即struct _mat)名稱空間中的下劃線開頭的任何標識符都是保留的。

+0

評論__reserved_ +1 – ryyker