I have to Create a dynamic array capable of holding 2*n Fractions. If the dynamic array cannot be allocated, prints a message and calls exit(1). It next fills the array with reduced random Fractions whose numerator is between 1 and 20, inclusive; and whose initial denominator is between 2 and 20, inclusive.
I ready did the function that is going to create the fraction and reduced it. this is what I got. When I compi开发者_如何学JAVAled and run this program it crashes I cant find out why. If I put 1 instead of 10 in the test.c It doesn't crash but it gives me a crazy fraction. If I put 7,8,or 11 in the test.c it will crash. I would appreciate if someone can help me.
FractionSumTester.c
Fraction randomFraction(int minNum, int minDenom, int max)
{
   Fraction l;
   Fraction m;
   Fraction f;
   l.numerator = randomInt(minNum, max);
   l.denominator = randomInt(minDenom, max);
   m = reduceFraction(l);
 while (m.denominator <= 1)
   {
        l.numerator = randomInt(minNum, max);
    l.denominator = randomInt(minDenom, max);
    m = reduceFraction(l);
   }
   return m;
}
Fraction *createFractionArray(int n)
{
   Fraction *p;
   int i;
   p = malloc(n * sizeof(Fraction));
   if (p == NULL)
   {
     printf("error");
     exit(1);
   }
   for(i=0; i < 2*n ; i++)
   {
      p[i] = randomFraction(1,2,20);
      printf("%d/%d\n", p[i].numerator, p[i].denominator);
   }
   return p;
}
this is the what I am using to test this two functions.
test.c
#include "Fraction.h"
#include "FractionSumTester.h"
#include <stdio.h>
int main()
{
      createFractionArray(10);
   return 0;
}
In your createFractionArray() function, you malloc() space for n items. Then, in the for loop, you write 2*n items into that space... which overruns your buffer and causes the crash.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论