簡體   English   中英

使用 getchar() 和 -O3 的奇怪行為

[英]Strange behavior using getchar() and -O3

我有這兩個功能

    void set_dram_channel_width(int channel_width){
      printf("one\n");
          getchar();
    }


    void set_dram_transaction_granularity(int cacheline_size){
      printf("two\n");
          getchar();
    }
    //output:
    one
    f //my keyboard input
    two
    one
    f  //keyboard input
    two
    one
    f  //keyboard input
    //No more calls

然后我將功能更改為:

    void set_dram_channel_width(int channel_width){
      printf("one\n");
    }


    void set_dram_transaction_granularity(int cacheline_size){
      printf("two\n");
      getchar();
    }
    //output
    one
    two 
    f //keyboard input
    //No more calls 

這兩個函數都由外部代碼調用,兩個程序的代碼是相同的,只是更改 getchar() 我得到了這兩個不同的輸出。 這是可能的還是我的代碼中確實有問題?

謝謝

這是我使用 GDB 獲得的 output**

對於第一個代碼

(gdb) break mem-dram.c:374
Breakpoint 1 at 0x71c810: file build/ALPHA_FS/mem/dramsim/mem-dram.c, line 374.
(gdb) break mem-dram.c:381
Breakpoint 2 at 0x71c7b0: file build/ALPHA_FS/mem/dramsim/mem-dram.c, line 381.
(gdb) run -d ./tmp/MyBench2/ 
one
f
[Switching to Thread 47368811512112 (LWP 17507)]

Breakpoint 1, set_dram_channel_width (channel_width=64)
(gdb) c
Continuing.
two
one
f

Breakpoint 2, set_dram_transaction_granularity (cacheline_size=64)
(gdb) c
Continuing.

Breakpoint 1, set_dram_channel_width (channel_width=8)
374     void set_dram_channel_width(int channel_width){
(gdb) c
Continuing.
two
one
f

對於第二個代碼

(gdb) break mem-dram.c:374
Breakpoint 1 at 0x71c7b6: file build/ALPHA_FS/mem/dramsim/mem-dram.c, line 374.
(gdb) break mem-dram.c:380
Breakpoint 2 at 0x71c7f0: file build/ALPHA_FS/mem/dramsim/mem-dram.c, line 380.
(gdb) run
one
two
f
[Switching to Thread 46985688772912 (LWP 17801)]

Breakpoint 1, set_dram_channel_width (channel_width=64)
(gdb) c
Continuing.

Breakpoint 2, set_dram_transaction_granularity (cacheline_size=64)
(gdb) c
Continuing.

Breakpoint 1, set_dram_channel_width (channel_width=8)
(gdb) c
Continuing.

由於您還沒有提供外部代碼(還沒有?),這里有一個猜測。

while(some condition) {
    foo1();
    foo2();
}
  • foo1 打印 ' one ' 然后等待一些輸入。 你輸入' f[enter] '。
  • foo1 消耗“ f ”。
  • foo2 打印 'two' 然后使用[enter] (換行符)。
  • 然后你 go 回到開始,這一切又發生了。

在您的第二個版本中, foo1() 不再讀取任何內容。

所以:

  • foo1 打印“ one
  • foo2 打印 ' two ' 然后等待一些輸入。 你輸入' f[enter] '
  • foo2 消耗' f '

剩下的唯一問題是為什么它會停止。 為了幫助您解決這個問題,我們必須看看(some condition)實際上是什么。

請注意,調用getchar()而不保留結果是相當不尋常的(如c = getchar(); )。 你有這樣做的理由嗎?

一個有用的 C 習語是:

(void) getchar(); 

強制轉換為 void 表明程序員知道他們正在丟棄返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM