Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process exited with return value 3221225477

Tags:

c

i am writing this code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int i;
fp = fopen("keimeno.txt","r");
fscanf(fp,"%d",i);
printf("%d\n",i);
    fclose(fp);
return 0;
}

and the file contains:

2
Yiannis Ioannou 356
3
Today
10347
If
345
And then none
1542
John Smith 743
2
My story
3940
Feedback
682
END

When I try to run it, it exits me value 3221225477 instead of printing the number 2..

Can anyone explain why?

like image 809
kostas Avatar asked Dec 15 '22 22:12

kostas


1 Answers

When you scan a number, you need to pass the address of the variable where you want to store the result:

fscanf(fp,"%d",&i);

where you have

fscanf(fp,"%d",i);
               ^  missing the & sign!

Your compiler really ought to have warned you - do you enable warnings when you compile?

What is happening here is that the fscanf function writes to the location given (in your case, it writes to whatever location is pointed to by the value of i, instead of writing to the location of i) . This can corrupt your memory in all kinds of nasty ways - resulting, in your case, in the program "running" for considerable time before crashing.

As @Brandin pointed out, there is a further problem with your code (although it's less likely to be the source of your problem). When you attempt to open a file, you should ALWAYS check that you succeeded. You do this with something like this:

#include <assert.h>
// at the top of the program


// attempt to open the file:
fp = fopen("keimeno.txt","r");
// and check whether you succeeded:
assert(fp != NULL); // this says "check fp is not NULL. Otherwise, quit."

Alternatively, you can make things a bit prettier with:

const char *fileName = "keimeno.txt";
const char *mode = "r";
if((fp=fopen(fileName, mode))==NULL) {
  printf("cannot open file %s\n", fileName);
  return -1;
}

It is almost always a good idea to put "hard wired values" near the start of your program, rather than embedding them in a function call.

like image 110
Floris Avatar answered Jan 02 '23 19:01

Floris