-2

I have appended my code below which open and read from 2 ascii files written in c. The code compiles without any problem, but when I execute the code, firstly, it is not properly reading the file, prints/reads all values as zeroes, secondly, gives a segmentation fault (core dumped) error, after it executes the printf command which is outside the loop. The file fpin has 22 rows and fpin1 has 2621440 rows. I was not able to find a workaround in this issue. I'll be thankful, if someone can help me to get a solution to this issue.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{

FILE *fpin,*fpin1;
int i,j,m[1000];
int *n1;
float radp[1000], decdp[1000];
float *rad1,*decd1,*temp1;

n1 = (int *)malloc(sizeof(int));
rad1 = (float *)malloc(sizeof(float));
decd1 = (float *)malloc(sizeof(float));
temp1 = (float *)malloc(sizeof(float));


if( (fpin = fopen("tmp","r")) == NULL)
{
printf("No such file\n");
exit(1);
}
if( (fpin1 = fopen("lfmap.txt","r")) == NULL)
{
printf("No such file\n");
exit(1);
}


for (i=0;i<22;i++){
fscanf(fpin,"%d %f %f",&m[i],&radp[i],&decdp[i]);
printf("%d %f %f\n",i,radp[i],decdp[i]);
}

for (j=0;j<2621440;j++){
fscanf(fpin1,"%d %f %f %f",&n1[j],&rad1[j],&decd1[j],&temp1[j]);
printf("%d %f %f %f\n",n1[j]+1,rad1[j],decd1[j],temp1[j]);
}

printf("%d\n",j);

fclose(fpin);
fclose(fpin1);
free(n1);
free(rad1);
free(decd1);
free(temp1);
}

Thanks, Krishnakumar

2 Answers2

3
n1 = (int *)malloc(sizeof(int));
rad1 = (float *)malloc(sizeof(float));
decd1 = (float *)malloc(sizeof(float));
temp1 = (float *)malloc(sizeof(float));

all the cases , you're allocating memory for a single element of that type.

Next,

fscanf(fpin,"%d %f %f",&m[i],&radp[i],&decdp[i]);
printf("%d %f %f\n",i,radp[i],decdp[i]);

You're accessing out-of-bound memory using index i. Behaviour is undefined.

Side Note:

  1. Always check for the success of fscanf() / scanf().
  2. Please do not cast the return value of malloc().
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2
n1 = (int *)malloc(sizeof(int));

n1 can hold only one integer and so the access n1[0] is valid but n1[1] is undefined behavior

The same goes for rest of your pointers. Also don't cast malloc()

Gopi
  • 19,784
  • 4
  • 24
  • 36