簡體   English   中英

釋放矩陣時出現分段錯誤

[英]Segmentation fault when freeing my matrix

我正在使用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);
}

這是錯誤:

_mat[i] = &tmpMatrix[i];

應該

_mat[i] = &tmpMatrix[0];

或更好

_mat[i] = tmpMatrix;

問題是你沒有正確分配它。 這個:

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);
    }

此外, _mat_lines_columns是C中的保留標識符,您不應該使用它們。 保留以普通(即_mat )或標記(即struct _mat )命名空間中具有文件范圍的下划線開頭的任何標識符。

以下是一些用於為字符串分配內存的函數,實際上是字符串數組,您可以根據需要輕松修改它們:

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);  
}

以下是如何修改(和使用)int的內容:(注意,它實際上只是識別sizeof(type)的差異)
另請注意:使用malloc()不會初始化值。 如果要保證每個元素的初始值(例如0 ),可以使用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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM