【问题标题】:printf statement printing previous printf statementprintf 语句打印上一个 printf 语句
【发布时间】:2015-11-30 15:54:54
【问题描述】:

我遇到了我见过的最奇怪的错误之一。

我有一个简单的程序,可以打印几个整数数组。

对数组进行排序,然后打印...

  place_in_buf(n100, 100);
  insertion(100);
  printf("\nThe number of comparisons in insertion sort for n=100 is: %d", insertion_count);
  insertion_count = 0;

  place_in_buf(n200, 200);
  insertion(200);
  printf("\nThe number of comparisons in insertion sort for n=200 is: %d", insertion_count);
  insertion_count = 0;

程序出现段错误,因为在执行第二个打印语句之前没有打印第一个打印语句。如下调试所示...

   95     */
   96     place_in_buf(n100, 100);
   97     insertion(100);
-> 98     printf("\nThe number of comparisons in insertion sort for n=100 is: %d", insertion_count);
   99     insertion_count = 0;
   100
   101    place_in_buf(n200, 200);
(lldb) n

Process 1139 stopped
* thread #1: tid = 0x1c96, 0x00000001000017b3 P3`insertion_comparison + 67 at HW8P3.c:99, queue = 'com.apple.main-thread', stop reason = step over
    frame #0: 0x00000001000017b3 P3`insertion_comparison + 67 at HW8P3.c:99
   96     place_in_buf(n100, 100);
   97     insertion(100);
   98     printf("\nThe number of comparisons in insertion sort for n=100 is: %d", insertion_count);
-> 99     insertion_count = 0;
   100
   101    place_in_buf(n200, 200);
   102    insertion(200);

   ... 

   101    place_in_buf(n200, 200);
   102    insertion(200);
-> 103    printf("\nThe number of comparisons in insertion sort for n=200 is: %d", insertion_count);
   104    insertion_count = 0;
   105
   106    place_in_buf(n400, 400);
(lldb) n
The number of comparisons in insertion sort for n=100 is: 4950
Process 1139 stopped
* thread #1: tid = 0x1c96, 0x00000001000017ef P3`insertion_comparison + 127 at HW8P3.c:104, queue = 'com.apple.main-thread', stop reason = step over
    frame #0: 0x00000001000017ef P3`insertion_comparison + 127 at HW8P3.c:104
   101    place_in_buf(n200, 200);
   102    insertion(200);
   103    printf("\nThe number of comparisons in insertion sort for n=200 is: %d", insertion_count);
-> 104    insertion_count = 0;

我已经在本地 Mac 和 Linux 服务器上尝试过,两者都在做同样的事情

我也尝试过重置我的 PRAM,但也没有成功。

有什么想法吗?

【问题讨论】:

  • 没有阅读完整的帖子,但看起来你可以在printf()的格式字符串末尾使用\n
  • 建议在printf()的末尾添加'\n'或添加fflush(stdout)。臭虫的来源闻起来像是在place_in_buf(n100, 100);insertion(100);
  • fflush(stdout) 也不走运
  • 从头开始,我正在编译错误的文件lol

标签: c debugging printing printf


【解决方案1】:

stdoutprintf 使用)的输出默认是行缓冲,这意味着缓冲区被刷新并实际写入换行符。

由于您只打印 leading 换行符而不是尾随,因此您将缓冲区中先前内容的输出直到换行符,换行符之后的所有内容都将被缓冲,直到您再次调用 printf换行。

您应该养成使用尾随换行符的习惯。

【讨论】: