Reputation: 1
The following program prints prime numbers between 1 and 10.
#include <stdio.h>
int* prime(int x,int y,int* range);
void main()
{
int *x,s=10;
int i=0;
x=prime(1,10,&s);
for(i=0;i<s;i++)
{
printf("%d\n",x[i]);
}
}
int* prime(int x,int y,int *range){
int num[100],i,j,flag,inc=0;
for(i=x;i<=y;i++)
{
flag=1;
for(j=2;j<=(i/2);j++)
{
if(i%j == 0)
flag=-1;
}
if(flag==1)
{
num[inc]=i;
inc++;
}
}
*range=inc;
//printf("$$%d$$",*range);
return num;
}
the output is 1 2 3 5 0 in the above case, but if we remove the the comment in printf statement in prime function and give as normal printf statement the output is 1 2 3 5 7 How is this even possible?? What's the bug here??
The compiler i used is GCC compiler in linux platform.
Upvotes: 0
Views: 2328
Reputation: 1263
You are passing the local variable address to the main. It is not a good practice. Scope of local variable is within that module. So you can directly pass your array to the prime and work on the result directly. Note: Your code works perfectly too without printf in the prime.. Undefined Behaviour.
#include <stdio.h>
void prime(int x,int y,int* range, int * arr);
void main()
{
int n[10],s=10;
int i=0;
prime(1,10,&s,n);
for(i=0;i<s;i++)
{
printf("%d\n",n[i]);
}
}
void prime(int x,int y,int *range,int *arr)
{
int i,j,flag,inc=0;
for(i=x;i<=y;i++)
{
flag=1;
for(j=2;j<=(i/2);j++)
if(i%j == 0) flag=-1;
if(flag==1) *(arr+inc++)=i;
}
*range=inc;
}
Upvotes: 0
Reputation: 22094
Your are allocating an int array on the stack. So when you return num;
it goes out of scope and the behaviour is undefined, because the pointer becomes invalid and you corrupt the stack.
You must allocate the array inside main and pass it to prime()
or malloc()
inside of prime()
and return that, freeing it in main.
Upvotes: 1
Reputation: 29266
Your prime()
method returns local variable num
which is sitting on the stack, so it's not in scope (aka invalid) after theprime()
call returns.
A couple of fixes:
num
static in prime
num
(remember to free it)num
into the prime
method.Upvotes: 3