hope someone can assist. I had this program running perfectly, moved a few lines of code from one function to another and it all fell apart.
I've included a snippet below from the top of the function until segfault. It happily outputs "did we get here?" but not the next statement, I've spent so many hours trying to figure this that I can't remember the working build I had to begin with
It (at least the section below) is supposed to copy a whole textfile to a string
Morals of the story: working code is better than 'correct' code, always copy working code before you try to tweak it.
void validateFile(FILE* file, char** menuStore, char** submenuStore)
{
char* temp = NULL;
size_t size;
boolean flag = true;
char first;
/*Loop Counter*/
int i;
fseek(file, 0, SEEK_END);
size = ftell(file) * sizeof(char);
fseek(file, 0, SEEK_SET);
if ((temp = malloc(size)) == NULL)
{
printf("\nUnable to allocate Memory, Program exiting");
exit(EXIT_FAILURE);
} else
{
for (i = 0; i < (size / sizeof(char)); i++)
{
temp[i] = fgetc(file);
}
printf("\n did we get here?");
printf("\nFile loaded, validating...");
While reading from a file you should not use loop like this-
for (i = 0; i < (size / sizeof(char)); i++)
{
temp[i] = fgetc(file);
}
You should check for EOF
condition while reading from a file-
i=0;
while((temp[i]=fgetc(file))!=EOF)
i++;
and make end of the string to \0
. That is the better way to do.
temp[i]='\0';