运行时错误与编译时错误

Errors at runtime vs errors at compile time

我们最近参加考试时遇到了这个问题:

考虑这段代码:

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

以下哪些说法是正确的?

A)程序在编译时产生错误

B)程序在运行时产生错误

C)。 . .

D)。 . .

我们无法使用编译器,所写的信息是我们唯一的东西。 正确答案最终是 B,运行时出错,有人能详细解释一下这是为什么吗?

我知道编译器会生成警告,但这里的重点是了解为什么编译器让我们首先编译这段代码而不是给我们一个错误。

我的猜测是 open,即使不返回一个指针(这是一个地址),给出的 fp 仍然是一个 int,所以在编译器看来这不是错误的语法,但是在运行时,它可能会尝试访问导致错误的私有内存地址。

p.s。 我知道正确的函数应该是 fopen,但这仍然不能解释为什么

此代码有两个具体问题:

  • open 的第二个参数需要 int 但传递的是 char *
  • open returns 一个 int 但那个值被分配给了一个 FILE *.

编译器将这些标记为警告而不是错误,因为该语言允许将指针转换为整数,以及将整数转换为指针。但是,这样做通常是实现定义的,通常(如本例)但并不总是表示有问题。

C standard 的第 6.3.2.3 节描述了这些转换:

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.