鍍金池/ 問答/C  C++/ 內存釋放問題

內存釋放問題


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

void printarr(int m,int n,int arr[n][n])
{
    for(int i= 0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            printf("%5d ",arr[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
void clearzero(int m,int n,int (*str)[n])
{
    /*定義兩個一維數(shù)組標識保存該行/列是否有零*/
    bool *row = (bool *)malloc(m * sizeof(bool));
    bool *col = (bool *)malloc(n * sizeof(bool));
    /*初始化*/
    /*添加memset與否決定程序運行是否正確*/
    memset(row, 0x0, m);
    memset(col, 0x0, n);
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(str[i][j] == 0)
            {
                row[i] = true;
                col[j] = true;
            }
        }
    }
    
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            /*當前元素所在行/列為0,置元素為0*/
            if(row[i] || col[j])
            {
                str[i][j] = 0;
            }
        }
    }
    free(row);
    row = NULL;
    
    free(col);
    col = NULL;
}



int main(int argc, const char * argv[])
{
    int str[3][3] = {{1,2,3},{0,1,2},{0,0,1}};
    clearzero(3,3,str);
    printarr(3,3,str);
    
    int cool[5][3] = {{1,2,3},{1,1,2},{0,2,1},{1,2,0},{2,3,4}};
    clearzero(5,3,cool);
    printarr(5,3,cool);
    return 0;
}

上面代碼中我申請了兩個bool類型的數(shù)組,釋放的話怎么釋放呢?
我直接在最后free(row) row = NULL; free(col) col = NULL;程序結果與預期不符,這是為什么呢?
這塊內存到底該怎么釋放呢?難道我要一個一個的遍歷這兩個數(shù)組,然后去釋放?
如果不添加如下兩行,程序運行結果錯誤:
memset(row, 0x0, m);
memset(col, 0x0, n);
這究竟是為什么呢?

回答
編輯回答
哚蕾咪

釋放部分沒錯。

free(row);
row = NULL;
free(col);
col = NULL;

這段代碼的問題是 malloc 之后沒有 memset。

2018年1月23日 14:40