开发者

Create a Fraction array

开发者 https://www.devze.com 2023-01-27 04:07 出处:网络
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).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消