Hi, so I have a code to sort my data files by adding new lines when the value of the first column increases. however, when i crank the size of these files up, the code runs into a segmentation fault, thus suggesting that malloc() needs to be used to reallocate the memory. however, i am confused as the argument of the malloc() function is simply the size of memory required, which I am not sure. I also don't exactly know to which variable needs reallocating. any help here would be much appreciated!
Code:
#include <string.h>
#include <math.h>
#include <stdio.h>
#define MAXLINE 100
int main()
{
printf("enter file name: ");
char filename[MAXLINE];
scanf("%s", filename);
FILE *newfile = fopen(filename, "r");
FILE *tempfile = fopen("tempfilename", "w");
int ch, nlines = 0;
while ((ch = fgetc(newfile)) != EOF)
{
if (ch == '\n')
{
nlines++;
}
}
float doub[nlines];
char line[MAXLINE], rest[nlines][MAXLINE];
rewind(newfile);
for (int i = 0; i < nlines; i++)
{
fgets(line, MAXLINE, newfile);
sscanf(line, "%f %s", &doub[i], rest[i]);
if (i > 0 && doub[i] > doub[i-1])
{
fputc('\n', tempfile);
}
fputs(line, tempfile);
}
fclose(newfile);
fclose(tempfile);
rename("tempfilename", filename);
return 0;
}