Programm crashing at fgets() in c

theboringkid

when I run my Program, which should read a simple File, it just crashes at the fgets() function. I get no errors in my IDE or from gcc. I know that there are similar Posts, but I couldn't figure out the Problem with them. So here is my code, and thanks for help!

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

char a[64];

int main() {
    FILE* fp;
    fopen("Memory.mem", "r");
    fgets(a, 64, (FILE*)fp);
    printf("%s\n", a);
    // the getchar is just that the Program doesn't close it self imeadiatly
    getchar();
    return 0;
}
//In the Memory.mem file is just "abcdefg"
Marko Borković

The problem is when you fopen you don't actually save the returned file pointer. When you call fgets fp is uninitialized, thus causing undefined behaviour.

You can fix it by instead of doing this:

FILE* fp;
fopen("Memory.mem", "r");

do this:

FILE* fp = fopen("Memory.mem", "r");

Also note that it is good practice to put a check if opening the file was successful.

FILE* fp = fopen("Memory.mem", "r");
if(fp == NULL){
    printf("Couldn't open file!\n");
    return EXIT_FAILURE;
}

And you should close the file once you are done using it with:

fclose(fp);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related