问题描述:

I am trying to write a program in C which uses malloc() to allocate memory for a 2d array, then I have to fill this array with data from a file (4 columns, 559 rows of numbers).

My program does compile, but it gives a SIGSEGV error in runtime.

This is the code:

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

int main(){

FILE *pf;

pf = fopen("Union_sin.txt","r");

int rows = 559;

int columns = 4;

int i =0;

int j=0;

float **matrix;

matrix = (float **)malloc(rows*sizeof(float *));

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

matrix[i] = (float *)malloc(columns*sizeof(float *));

}

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

for (j=0; j<columns; j++)

fscanf(pf,"%f\t",&matrix[i][j]);

}

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

for(j=0;j<columns;j++){

printf("%f\t", matrix[i][j]);}

printf("\n");}

for(i=0;i<rows;i++) free(matrix[i]);

free(matrix);

return 0;}

As you can imagine I am not very skilled so, please, try to be kind and clear.

网友答案:

This line:

   matrix[i] = (float *)malloc(columns*sizeof(float *));

Should be

   matrix[i] = malloc(columns*sizeof(float));

Note that as well as allocating the correct amount of memory, the redundant and dangerous cast has been removed. (You should remove the cast on the first malloc too.)

Another problem: you are totally failing to check for errors on the call to fopen. Assuming that the file has been successfully opened is a recipe for disaster. Structure your code like this:

FILE * pf = fopen("Union_sin.txt","r");
if (f == NULL)
{
    // report error
}
else
{
    // do your stuff

    fclose(pf);
}
相关阅读:
Top