Having some problems with this bit of code allocating memory correctly:
I get to the middle of the 1st function call and during runtime I get:
0 [main] a 3888 handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
9946[main] a 3888 stackdump: Dumping stat trace to a.exe.stackdump
There is a comment in the code that notates where it seems to be crashing.
Basic concept is to ask user for name of file, allocate memory for X number of structs to hold the data of the file. Then store the file in an array of structs.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char lname[30];
char fname[30];
int score;
}data;
data *read_file (char file[],int *numbstudents);
int main()
{
char filename[20];
int numbstudents;
data *student_list;
printf("Please enter the name of the file containing the grades.\n");
scanf ("%s", filename);
printf("File name recorded.\n");
student_list = read_file (filename, &numbstudents);
free (student_list);
return 0;
}
data *read_file(char file[], int *numbstudents)
{
FILE *fp;
int i;
data *list;
printf("Attempting to open file...\n");
fp = fopen(file, "r");
if (fp == NULL)
{
printf("File cannot be opened");
exit(0);
}
else
{
printf("File opened successfully.\n");
}
fscanf ( fp, "%d", &numbstudents);
printf ("Total Students: %d \n", numbstudents);
printf ("Allocating Memory\n");\\This is where it is crashing
list = (data*)malloc((*numbstudents)*sizeof(data));
for (i = 0; i < *numbstudents; i++)
{
fscanf( fp, "%s", list[i].lname);
fscanf( fp, "%s", list[i].fname);
fscanf( fp, "%d", list[i].score);
}
fclose (fp);
return list;
}
This is an example of the file to open:
Code:
6
Ball Adam 80
Arnold Joshua 60
Scot Michael 80
Cook Bret 60
Davis Ronald 60
Fox Brian 80
Singh Jaadu 91
Any assistance why this might not run would be appreciated.