为什么访问我的矩阵给我一个赛格故障? [英] Why does accessing my matrix give me a seg fault?

查看:123
本文介绍了为什么访问我的矩阵给我一个赛格故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以往我尝试访问我的基质是行*** 我得到一个赛格故障。
通过简单的操作,如(矩阵[i] [j]的 - > VBIT == 00){INT VBIT} 给我一个分段错误。我假设它是在构造函数中,但我似乎无法找到的问题。任何人都看到了吗?

 行*** getSets(INT宽度,高度INT){
INT I;
诠释J;
行*温度;
行线;的printf(请%D设定%d条线的\\ n,高度,宽度);行***矩阵=(行***)释放calloc(高度的sizeof(线**));
对于(i = 0; I<高度;我++){
    矩阵[I] =(行**)释放calloc(宽度的sizeof(线*));
}///将所有VBITS为0
对于(i = 0; I<高度;我++){
    为(J = 0; J<宽度; J ++){
        TEMP =矩阵[I] [J]。
        TEMP =的malloc(sizeof的(线));
        TEMP-&G​​T; VBIT = 0;
        TEMP->标签= 0;
        TEMP-&G​​T; LASTUSED = 0;
    }
}
返回矩阵;}


解决方案

您永远只能分配给温度,而不是实际的矩阵元素:

  TEMP =矩阵[I] [J]。
TEMP =的malloc(sizeof的(线));

做到这一点,而不是:

 矩阵[I] [J] =的malloc(sizeof的(线));
TEMP =矩阵[I] [J]。

或者

 为(J = 0; J<宽度; J ++){
    TEMP =的malloc(sizeof的(线));
    memset的(温度,0,sizeof的(线));
    矩阵[I] [J] =气温;
}

另外,你真的应该真正检查和释放calloc的malloc的结果。

When ever I try to access my matrix which is Line*** I get a seg fault. A simple operation such as (matrix[i][j]->vbit == 00),{int vbit} gives me a segmentation fault. I am assuming it is within the constructor, but I can't seem to find the issue. Anyone see it?

Line ***getSets(int width, int height){
int i;
int j;
Line *temp;
Line line;

printf("Make %d sets with %d lines\n",height,width);

Line*** matrix = (Line***)calloc(height,sizeof(Line**));


for(i=0;i < height;i++){
    matrix[i] = (Line**)calloc(width,sizeof(Line*));
}    

/// Set all vbits to 0
for(i = 0; i < height;i++){
    for(j = 0;j <width; j++){
        temp = matrix[i][j];
        temp = malloc(sizeof(Line));
        temp->vbit = 0;        
        temp->tag = 0;
        temp->lastUsed = 0;
    }
}
return matrix;}

解决方案

You only ever allocate to temp, not your actual matrix element:

temp = matrix[i][j];
temp = malloc(sizeof(Line));

Do this instead:

matrix[i][j] = malloc(sizeof(Line));
temp = matrix[i][j];

Or

for(j=0; j<width; j++) {
    temp = malloc(sizeof(Line));
    memset(temp, 0, sizeof(Line));
    matrix[i][j] = temp;
}

Plus, you should really really be checking the result of calloc and malloc.

这篇关于为什么访问我的矩阵给我一个赛格故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆