Reputation: 175
I have written code that generates a matrix with NODES rows and each row has a user specified number of columns (see node_degree below). I then fill each entry in the matrix with some value (the value doesn't matter).
When I build the program on Fedora using Geany, I receive no error messages. However, when I run the program I get:
./geany run script.sh line 5: 3586 Segmentation fault (core dumped)"./ ad_matrix_outside_main
Note: ad_matrix_outside_main is the name of the c file.
Here is the program:
#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);
}
What could be causing the error? I have a feeling my notation might be the problem.
Upvotes: 2
Views: 107
Reputation: 757
#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) );
//here you malloc for 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;
//here you assign for 10! }
for(i=0; i<NODES; i++)
{
free( matrix[i] );
}
free(matrix);
return(0);
}
Upvotes: 1