2015-03-30 1 views
-2

Если я прокомментирую строку printf в функции dicksonsmethod, я получаю ошибку сегментации. Если я оставлю его в пробегах кода и выдаст правильный ответ. Зачем? Я включил весь код, как только часть, вероятно,Почему я получаю ошибку сегментации, когда комментирую инструкцию printf

#include<stdio.h> 
#include <time.h> 
#include <math.h> 

int bruteforce(int max){ 
} 
int bruteforcerefined(int max){ 
} 

int dicksonsmethod(int max){ 
printf("The Dickson method\n");// If I comment out this line I get a Segmentation fault. 
int r,dm,fp; 
int a=1,b=2,c=3; 
int perimeter,multiplier; 
int paircount=0; 
int factorpairs[2][20]; 

for (r=2;;r+=2){ // infinite loop 
    dm=r*r/2; 

    paircount=0;// Get the count of factor pairs, and the pairs of factors 
    for (fp=1;fp<(dm/2)+1;fp++){ 
     if (dm%fp==0){ 
      if(fp >=dm/fp){ // fp >=dm/fp to avoid duplicating pairs in reverse 
       break; // do not want to get reverse facor pairs 
      } 
      paircount+=1; 
      factorpairs[paircount][0]=fp; 
      factorpairs[paircount][1]=dm/fp; 
     } 
    } 
    for (fp=1;fp<=paircount;fp++){ // for each Dickenson pair 
     a=r+factorpairs[fp][0]; // get the pythagorean triplet 
     b=r+factorpairs[fp][1]; 
     c=r+factorpairs[fp][0]+factorpairs[fp][1]; 
     perimeter=a+b+c; 
     if(max%perimeter==0){ // and see if it will scale to required size 
      multiplier=(int)max/perimeter; 
      //   printf("Sides %d %d %d as a triplet, the sum being %d, from factor pairs %d and %d \n",a,b,c,perimeter=a+b+c,factorpairs[fp][0],factorpairs[fp][1]); 
      return a*b*c*multiplier*multiplier*multiplier; 
     } 
    } 
} 
} 

int main() 
{ 
int max=1000; 
char str; 
while (1){ 
printf("Compare various methods of finding Pythagorean Triples to fullfil the specified conditions\n"); 
printf("1 - The Brute Force method.\n"); 
printf("2 - The Brute Force method, refined.\n"); 
printf("3 - The Dickson\'s method.\n"); 
printf("The Fibbonacci method, does not product usable triplets in a timely manner.\n"); 
printf("The Squared Difference, special method, does not product usable triplets in a timely manner.\n"); 
printf("The Squared Difference, general method, does not product usable triplets in a timely manner.\n"); 
printf("Enter a number 1 - 3 to execute or E to exit:- "); 
scanf(" %c",&str); 
printf("\n\n\n"); 
clock_t begin, end; 
double time_spent; 
begin = clock(); 
/* here, do your time-consuming job */ 
if (str == '1') { 
    printf("Brute force produces %d\n",bruteforce(max)); 
} 
if (str == '2') { 
    printf("Checking multiples of triplets produces %d\n",bruteforcerefined(max)); 
} 
if (str == '3') { 
    printf("The Dickson\'s method produces %d\n",dicksonsmethod(max)); 
} 
end = clock(); 
time_spent = (double)(end - begin)/CLOCKS_PER_SEC; 
printf(" and took %f seconds",time_spent); 
if(str == 'E' || str == 'e'){ 
    return 1; 
}printf("\n\n\n"); 
} 
} 
+0

Возможно, вы попадаете в память, которая не принадлежит вам. – immibis

+0

Вы пробовали запустить его в отладчике, чтобы найти строку, которая падает? – teppic

ответ

0

Вы развращают стек, который является причиной аварии. Я не прохожу через ваш алгоритм, но очевидно, что ваш массив factorpairs будет выписан за пределы. Быстрый отладки смотреть paircount производит для меня:

Old value = 1 
New value = 2 
dicksonsmethod (max=1000) at a.c:32 
32   factorpairs[paircount][0] = fp; 

т.е. вашей функции в какой-то момент пытается выписать пределы, так как paircount стал 2.

Причина, по которой работает с printf это потому, что вы на неопределенной территории поведения.

+0

Спасибо. Изменяя int factorpairs [2] [20]; к int factorpairs [5] [20]; проблема уходит. –

Смежные вопросы