内存释放问题


#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])
{
    /*定义两个一维数组标识保存该行/列是否有零*/
    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类型的数组,释放的话怎么释放呢?
我直接在最后free(row) row = NULL; free(col) col = NULL;程序结果与预期不符,这是为什么呢?
这块内存到底该怎么释放呢?难道我要一个一个的遍历这两个数组,然后去释放?
如果不添加如下两行,程序运行结果错误:
memset(row, 0x0, m);
memset(col, 0x0, n);
这究竟是为什么呢?

阅读 1.8k
1 个回答

释放部分没错。

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

这段代码的问题是 malloc 之后没有 memset。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题