为什么这段代码会陷入死循环?

Why this code fall into an infinite loop?

LLVM 版本 5.0.0

我写了这段代码并用 clang/llvm 构建。 但是,我无法理解为什么这段代码会转换为无限循环。

此代码是我用于构建的 C++ 代码。

#include <stdio.h>

int foo()
{
  for (int j= 0; j < 23; j++)
    putchar('a');
}
int main()
{
  foo();
}

我使用了以下命令行。

clang -O0 a.cpp // a.out not working
clang -O1 a.cpp
-O2 -O3 ... also

我也能在 LLVM-IR 中找到一个错误。

clang -S -O1 -emit-llvm a.cpp
clang -S -O1 -mllvm -disable-llvm-optzns -emit-llvm a.cpp 
   + opt -S -O1 a.ll

define i32 @_Z3foov() local_unnamed_addr #0 {
entry:
  br label %for.cond

for.cond:                                         ; preds = %for.cond, %entry
  %call = tail call i32 @putchar(i32 97)
  br label %for.cond
}

但这段代码运行良好。

int main()
{
  for (int j= 0; j < 23; j++)
    putchar('a');
}

您的函数 int foo()int main() 缺少 return 语句。这可能会导致 ISO C++ 标准第 6.6.3 节中指定的未定义行为:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

您应该在 clang -O0 a.cpp

之后看到一个错误
a.cpp:7:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
1 warning generated.

这是一个适合您的版本:

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

int foo()
{
  for (int j= 0; j < 23; j++)
    putchar('a');
  return 0;
}

int main()
{
  foo();
  return EXIT_SUCCESS;
}