简体   繁体   中英

Segmentation Fault before even starting execution

I wrote this code yesterday, during a live contest on codeforces, and it produces segmentation fault before even executing the first line in main(). The program didn't even print "test"

#include <bits/stdc++.h>
using namespace std;

int main () {
    cout << "test";
    int t;
    cin >> t;
    while (t--) {
        int n, s, k, ans = 0;
        cin >> n >> s >> k;
        int arr[n+1];
        memset(arr, 0, sizeof arr);
        for (int i = 0; i < k; i++) {
            cin >> t;
            arr[t] = 1;
        }
        int i = 0;
        while (true) {//cout<<"test";
            if (s+i <= n && arr[s+i] == 0) break;
            if (s-i > 0 && arr[s-i] == 0) break;
            if (s-i <= 0 && s+i > n) break;
            i++;
        }
        cout << i << endl;
    }
    return 0;
}

Your program does not print "test" because you need to flush stdout . If you do not flush it, SO will keep that text in a buffer and might wait for an appropriate moment to output it. Instead, force SO to print it using:

cout << "test" << std::endl;

Or

flush(stdout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM