- #1
nenyan
- 67
- 0
I wrote a program to read a txt file. When its running, system appear "Segmentation fault <core dumped>"
the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BUF 1024
#define pi 3.14159
typedef struct skymapdata
{
double ra;
double dec;
double p;
double pn;
} skydata;
/* This function is for readding skymap*/
int
readskymap( FILE *fp, skydata **sky)
{
skydata *sky1;
int i=0, n=BUF; /* n is the buffer. */
if ( !(*sky=(skydata *)malloc(n*sizeof(skydata))))
printf("memory error 1\n");
while (!feof(fp))
{ fscanf(fp, "%lf %lf %lf %lf", (*sky+i)->ra, (*sky+i)->dec, (*sky+i)->p, (*sky+i)->pn);
i++;
if (i==(n-1)) /*the number of lines is going to be longer than buffer. */
{
if(!(sky1=realloc(*sky, 2*n*sizeof(skydata))) ) {
printf("memory error 2\n"); }
*sky=sky1;
n*=2; } /*double the buffer*/
}
return i; /* Returning i tell us the accurate number.*/
}
int
main()
{
int i, n1;
skydata *sky;
FILE *fp;
if ( !( fp=fopen("skymap.txt", "r"))) {
printf ("cannot open the skymap.txt file\n");
return 1;}
n1=readskymap(fp, &sky);
for (i=0; i<n1; i++)
printf("%e %e %e %e\n", sky.ra, sky.dec, sky.p, sky.pn);
}
skymap.txt:
3.222 4.323 0.23 0.32
5.434 43.34545 0.3434 0.22
the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BUF 1024
#define pi 3.14159
typedef struct skymapdata
{
double ra;
double dec;
double p;
double pn;
} skydata;
/* This function is for readding skymap*/
int
readskymap( FILE *fp, skydata **sky)
{
skydata *sky1;
int i=0, n=BUF; /* n is the buffer. */
if ( !(*sky=(skydata *)malloc(n*sizeof(skydata))))
printf("memory error 1\n");
while (!feof(fp))
{ fscanf(fp, "%lf %lf %lf %lf", (*sky+i)->ra, (*sky+i)->dec, (*sky+i)->p, (*sky+i)->pn);
i++;
if (i==(n-1)) /*the number of lines is going to be longer than buffer. */
{
if(!(sky1=realloc(*sky, 2*n*sizeof(skydata))) ) {
printf("memory error 2\n"); }
*sky=sky1;
n*=2; } /*double the buffer*/
}
return i; /* Returning i tell us the accurate number.*/
}
int
main()
{
int i, n1;
skydata *sky;
FILE *fp;
if ( !( fp=fopen("skymap.txt", "r"))) {
printf ("cannot open the skymap.txt file\n");
return 1;}
n1=readskymap(fp, &sky);
for (i=0; i<n1; i++)
printf("%e %e %e %e\n", sky.ra, sky.dec, sky.p, sky.pn);
}
skymap.txt:
3.222 4.323 0.23 0.32
5.434 43.34545 0.3434 0.22