我有一个我见过的最奇怪的错误。
我有一个打印几个整数数组的简单程序。
对数组进行排序,然后打印...
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;
程序是seg faulting,因为在执行第二个print语句之前不会打印第一个print语句。如以下调试所示...
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,但那也没有运气。
有什么想法吗?
答案 0 :(得分:3)
输出到stdout
(由printf
使用)默认为行缓冲,这意味着缓冲区已刷新并实际写在换行符上。
由于您只打印前导换行符而不是尾随,因此您可以获得缓冲区中之前内容的输出直到换行符,换行符之后的所有内容都将被缓冲,直到您调用{{1}再次使用换行符。
你应该养成使用尾随换行符的习惯。