[英]printf statement printing previous printf statement
我有我见过的最奇怪的错误之一。
我有一个简单的程序可以打印几个整数数组。
对数组进行排序,然后打印...
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,但这也没有运气。
有任何想法吗?
默认情况下,输出到stdout
(由printf
)是line buffered ,这意味着缓冲区被刷新并实际写入换行符。
由于您只打印前导换行符而不打印尾随,因此您将获得缓冲区中先前内容的输出,直到换行符,换行符之后的所有内容都将被缓冲,直到您再次使用换行符调用printf
为止。
您应该养成使用尾随换行符的习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.