【问题标题】:Memory allocation for a matrix矩阵的内存分配
【发布时间】:2013-06-24 09:06:06
【问题描述】:

我编写的代码可以生成一个包含 NODES 行的矩阵,并且每行都有用户指定的列数(请参阅下面的 node_degree)。然后我用一些值填充矩阵中的每个条目(值无关紧要)。

当我使用 Geany 在 Fedora 上构建程序时,我没有收到任何错误消息。但是,当我运行程序时,我得到:

./geany run script.sh line 5: 3586 Segmentation fault (core 转储)”。/ ad_matrix_outside_main

注意:ad_matrix_outside_main 是 c 文件的名称。

这是程序:

#include <stdio.h>
#include <stdlib.h>
#define NODES (10)
#define CONNECTED (5)

int main()
{
int i, j;
double **matrix;

matrix = (double **)malloc(sizeof(double *)*NODES); 

int node_degree[CONNECTED]; //Example: 5 nodes are connected (have non-zero degree).    

for(i=0; i<CONNECTED; i++)
{
    printf("Enter degree of node %d\n", i);  //Index is node, value is degree. 
    scanf("%d", &node_degree[i]);                               
} 

for(i=0; i<CONNECTED; i++)
{
    matrix[i] = (double*)malloc( sizeof(double)* (node_degree[i] + 1) );
}

for(i=0; i<NODES; i++) 
{

    for(j=0; j<node_degree[i]; j++) 
    {
        matrix[i][j] = j; //j can be the node that node i connected to. 
    }
    matrix[i][j] = NODES; 
}

for(i=0; i<NODES; i++)
{
    free( matrix[i] );
}

free(matrix);
return(0);
}

什么可能导致错误?我觉得我的符号可能是问题所在。

【问题讨论】:

  • 每当您遇到分段错误时,您应该使用-g gcc 选项编译您的代码,然后使用 bash 命令ulimit -c unlimited 启用核心转储并执行您的二进制文件,这样您就可以获得一个核心-倾倒。然后就可以通过gdb和backtrace知道crash的真正原因了

标签: c dynamic malloc


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#define NODES (10)
#define CONNECTED (5)

int main()
{
int i, j;
double **matrix;

matrix = (double **)malloc(sizeof(double *)*NODES); 

int node_degree[CONNECTED]; //Example: 5 nodes are connected (have non-zero degree).    

for(i=0; i<CONNECTED; i++)
{
    printf("Enter degree of node %d\n", i);  //Index is node, value is degree. 
    scanf("%d", &node_degree[i]);                               
} 

for(i=0; i<CONNECTED; i++)
{
    matrix[i] = (double*)malloc( sizeof(double)* (node_degree[i] + 1) );

//这里你 malloc 为 5 }

for(i=0; i<NODES; i++) 
{

    for(j=0; j<node_degree[i]; j++) 
    {
        matrix[i][j] = j; //j can be the node that node i connected to. 
    }
    matrix[i][j] = NODES;

//在这里你分配10! }

for(i=0; i<NODES; i++)
{
    free( matrix[i] );
}

free(matrix);
return(0);
}

【讨论】:

  • 谢谢!我应该已经发现了。
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 2015-05-29
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2017-10-07
  • 1970-01-01
相关资源
最近更新 更多