Why this program fails for larger input value ?


P

pereges

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

int main(void)
{
unsigned long int numpoints;
printf("Enter num of points\n");
scanf("%lu", &numpoints);
unsigned long int numpointsx = sqrt((double)numpoints);
unsigned long int numpointsy = sqrt((double)numpoints);
numpoints = numpointsx * numpointsy;
unsigned long int i = 0;
typedef struct point
{
float x, y;
} point;
point *pointinarray;

pointinarray = calloc(sizeof(point), numpoints);
float xlength, ylength;
xlength = ylength = 20;
float xmin, ymin;
xmin = ymin = -10;
float xmax, ymax;
xmax = ymax = 10;
float xsize = xlength /( numpointsx-1);
float ysize = ylength / (numpointsy-1);

/* This the place where the error occurs */

unsigned long int xi, yi;
for ( yi = 0; yi <= numpointsy; ++yi)
{
for (xi = 0; xi <= numpointsx; ++xi)
{
pointinarray.x = xmin + xi * xsize;
pointinarray.y = ymin + yi * ysize;
++i;
}
}

printf("i: %lu xmax: %f ymax: %f\n",i, pointinarray[i-1].x,
pointinarray[i-1].y);
return 0;

}
 
Ad

Advertisements

J

Jens Thoms Toerring

pereges said:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
unsigned long int numpoints;
printf("Enter num of points\n");
scanf("%lu", &numpoints);
unsigned long int numpointsx = sqrt((double)numpoints);
unsigned long int numpointsy = sqrt((double)numpoints);
numpoints = numpointsx * numpointsy;
unsigned long int i = 0;
typedef struct point
{
float x, y;
} point;
point *pointinarray;
pointinarray = calloc(sizeof(point), numpoints);

Using calloc() here is a waste of time - setting the bits of
the elements of the structures does not guarantee that the
values they contain are initialized to 0 as long as they're
not integers. So malloc() would be faster since it doesn't
have to zero all the memory.
float xlength, ylength;
xlength = ylength = 20;
float xmin, ymin;
xmin = ymin = -10;
float xmax, ymax;
xmax = ymax = 10;
float xsize = xlength /( numpointsx-1);
float ysize = ylength / (numpointsy-1);
/* This the place where the error occurs */
unsigned long int xi, yi;
for ( yi = 0; yi <= numpointsy; ++yi)
{
for (xi = 0; xi <= numpointsx; ++xi)

You're using elements past the end of the array you allocated.
'yi' must always be less than 'numpointsy' and 'xi' less
than 'numpointsx'. Or you would have to allocate an array
with '(numpointsy + 1) * (numpointsx +1)' elements.
{
pointinarray.x = xmin + xi * xsize;
pointinarray.y = ymin + yi * ysize;
++i;
}
}

Regards, Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top