जब मैं gcc
के साथ संकलित निम्न कोड चलाता हूं (केवल विकल्प चालू है -std=c99
) और निष्पादन योग्य चलाएं, मुझे एक सेगमेंटेशन गलती मिलती है (msgstr "कोर कोर डंप किया गया)।यह रिकर्सिव कोड क्यों एक segfault फेंक देता है?
वह क्यों है?
#include <stdio.h>
int count_factors(int n, int i) {
int m = n;
if (m == i) {
return 1;
} else if (m % i == 0) {
while (m % i == 0) m = m/i;
return 1 + count_factors(m, i);
} else {
return count_factors(m, i+1);
}
}
int main() {
int streak_size = 4;
int streak = 0;
int solution = 0;
int n = 2;
while (solution == 0) {
n += 1;
int c = count_factors(n, 2);
if (c == streak_size) {
streak += 1;
} else {
streak = 0;
}
if (streak == streak_size) solution = n;
}
printf("%i", solution);
return 0;
}
क्योंकि आप कभी भी 'count_factors' में अपने रिकर्सन से बाहर नहीं निकलते हैं। 'Printf ("% d% d \ n ", n, i);' count_factors' की शुरुआत में 'और आप समझेंगे। –
ओह विडंबना, 'स्टैक ओवरफ्लो' नामक साइट पर। –
संकलन करते समय आपको हमेशा चेतावनियां सक्षम करनी चाहिए, उदाहरण के लिए '-Wall'। ध्यान दें कि यह सामान्य सलाह है और आपकी विशेष समस्या को हल करने में मदद नहीं कर सकती है। –