B.Castarunza
B.Castarunza

Reputation: 167

Errors at runtime vs errors at compile time

We recently took an exam were we got this question:

Consider this fragment of code:

FILE * pFile;
pFile = open ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "PI");

Which of the following statements are true?

A)The program generates error at compile time

B)The program generates error at runtime

C) . . .

D) . . .

We couldn't use the compiler, and the information wrote is the only thing we had. The correct answer ended up being B, error at runtime, can someone explain me thoroughly why that is?

I know the compiler generates a warning, but the point here is to understand why the compiler let us compile this code in the first place instead of giving us an error.

My guess is that open, even though doesn't give a pointer back(which is an address), gives the fp which is still an int, so in the eyes of the compiler isn't wrong syntax, but at runtime it probably tries to access a private memory address which leads to an error.

p.s. I know that the correct function should have been fopen, but that still doesn't explain why

Upvotes: 1

Views: 295

Answers (1)

dbush
dbush

Reputation: 224822

This code has two specific issues:

  • The second parameter to open expects an int but a char * is passed instead
  • open returns an int but that value is assigned to a FILE *.

The compiler flags these as warnings instead of errors because the language allows a pointer to be converted to an integer, and for an integer to be converted to a pointer. However, doing so is generally implementation defined and usually (as in this case) but not always indicates a problem.

Section 6.3.2.3 of the C standard describes these conversions:

5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type,the behavior is undefined. The result need not be in the range of values of any integer type.

Upvotes: 2

Related Questions